响应始终是整个 ajax 数据包



我总是得到整个ajax数据包,而不是简单的响应(true/false(作为这个函数的返回(responseJSON.success/responseText.success(。否则,浏览器会向我发送错误或错误结果,其中包含所述内容

function isUnique(inputObject) {
let type = $(inputObject).attr('id');
let res = $.ajax({
url: '/dbajax.php',
method: 'POST',
data: {[type]: $(inputObject).val()},
dataType: 'JSON',
success: function(data) { return data },
error: function(data) { }
})
console.log(res.responseJSON.success); // -> error: Cannot read property 'success' of undefined
console.log(res.responseJSON); // -> undefined
return res;
}
<?php
require('db/dbqueries.php');
if(isset($_POST['username'])){
$login_username = select_login_where_username ($_POST["username"]);
echo json_encode(array('success' => empty($login_username),));
}
if(isset($_POST['email'])){
$profile_email = select_profile_email_where_email ($email);
echo json_encode(array('success' => empty($profile_email),));
}
?>

您的问题与 $.ajax 是异步的事实有关。因此,如果您在 $.ajax 之后编写内容,它将在处理请求之前完成。您应该在成功函数中执行所有操作。

function isUnique(inputObject) {
let type = $(inputObject).attr('id');
let res = $.ajax({
url: '/dbajax.php',
method: 'POST',
data: {[type]: $(inputObject).val()},
dataType: 'JSON',
success: function(data) { console.log(data)},
error: function(data) { console.log(data) }
})

}
<?php
require('db/dbqueries.php');
if(isset($_POST['username'])){
$login_username = select_login_where_username ($_POST["username"]);
echo json_encode(array('success' => empty($login_username),));
}
if(isset($_POST['email'])){
$profile_email = select_profile_email_where_email ($email);
echo json_encode(array('success' => empty($profile_email),));
}
?>

您正在尝试在 ajax 请求完成之前访问响应 JSON。 您需要等待 ajax 完成才能使用它。有两种方法可以做到这一点 -

正如 robinvrd 提到的,使用成功和错误函数:

function isUnique(inputObject) {
let type = $(inputObject).attr('id');
let res = $.ajax({
url: '/dbajax.php',
method: 'POST',
data: {[type]: $(inputObject).val()},
dataType: 'JSON',
success: function(data) { 
console.log(data.success); //this will fire when the ajax request is finished and return the data
},
error: function(data) {
console.error(data); //this will tell you of any errors after the request has been made
}
})
return res;
}

或者在请求对象上使用回调:

function isUnique(inputObject) {
let type = $(inputObject).attr('id');
let res = $.ajax({
url: '/dbajax.php',
method: 'POST',
data: {[type]: $(inputObject).val()},
dataType: 'JSON'
})
res.done(function(result) {
console.log(res.responseJSON.success); 
});
res.fail(function( jqXHR, textStatus) {
console.error("Request failed: " + textStatus);
});
return res;
}

最新更新