开发者

AJAX JSON + PHP JSON error

I've got a jQuery AJAX code, which recieves JSON-type data from php file. Wihout dataType: "json" everything is ok. But I need JSON-type data. Te开发者_如何学Cxt recieved is a valid JSON code

{"ok":"false","answer":"All fields must be filled"}

But when I user dataType, I've got an error

Object "parsererror" SyntaxError

Here's JS code:

    $.ajax({
        url : "testing/regtest.php",
        type : "POST",
        dataType: "json",
        data : {
            mail : $('#mail_field').val(),
            username : $('#username_field').val(),
            password : $('#password_field').val(),
            password_2 : $('#rep_password_field').val()
        },
        success : function(data) {
            console.log(data.ok);
        },
        error: function(a,b,c) { console.log(a,b,c); }
    });

Thanks for any help!

Update: Here's php server-side code: http://jsfiddle.net/VfQbz/1/

Update 2: It works in IE9 but doesn't work in chrome


I'm not quite sure if this works, but IMHO the problem is PHP's lousy JSON encoding function. Try:

if (check_post() === true) {
    $password = $_POST['password'];
    $password2 = $_POST['password_2'];
    $username = $_POST['username'];
    $mail = $_POST['mail'];
    if (valid_data($password, $password2, $username, $mail) === true){
        $answer = json_encode(array("ok" => "true", "answer" =>     $service_messages["account_registered"]));
        echo "'".$answer."'"; // Note the additional single quotes
    }
}

By digging into the jQuery source I found the error to occur in the response parsing. Hope it works.


Does your PHP code sets the correct header?

header('Content-type: application/json');


Just to cover all the bases: are you sure your jQuery is up-to-date and not altered in any way?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜