我有一张登记表,正在使用$。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请求的成功回调?


当前回答

在我的情况下,错误是这是在服务器端,因此它返回一个HTML

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

其他回答

success回调函数有两个参数:

success: function (data, textStatus) { }

还要确保submit1.php设置了正确的内容类型头:application/json

我遇到了同样的问题,我用这种方法解决了它: 我的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.如果有什么地方不对,我很抱歉,但这是我在这个论坛上的第一个评论:)

我使用XML将结果从服务器上的php带回网页,我有相同的行为。

在我的例子中,原因是结束标记与开始标记不匹配。

<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <result>
        <status>$status</status>
        <OPENING_TAG>$message</CLOSING_TAG>
    </result>";
?>

在我的情况下,错误是这是在服务器端,因此它返回一个HTML

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

确保在PHP文件中生成JSON格式的数据之前不打印(回显或打印)任何文本/数据。这可以解释,你得到一个-成功200 OK-但你的成功事件仍然失败在你的javascript。可以通过检查firebug中POST submit1.php的“Network - Answer”部分来验证脚本接收的内容。