简体   繁体   中英

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. Text 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.

您的PHP代码是否设置了正确的标头?

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

只是为了覆盖所有基础:您确定您的jQuery是最新的并且没有任何改变吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM