我有一张登记表,正在使用$。Ajax来提交。
这是我的AJAX请求:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
在我的submit1.php文件中,我检查了数据库中字段电子邮件地址和用户名的存在。
我希望显示一个错误消息,如果这些值存在而不刷新页面。
我如何将此添加到我的AJAX请求的成功回调?
我遇到了同样的问题,我用这种方法解决了它:
我的ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
好的。问题不在于json,而在于php响应。
之前:我的php回答是:
echo 'item';
现在:
$variable = 'item';
echo json.encode($variable);
现在我的成功工作。
PS.如果有什么地方不对,我很抱歉,但这是我在这个论坛上的第一个评论:)
添加'error'回调函数(就像'success'一样):
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
以我为例,我在控制台看到:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.