简体   繁体   中英

Syntax Error{} AJAX success cannot read JSON returned from PHP

I need some help here. I'm sending simple request to server, and the return I expected is JSON as data type. But when I checked in development tools console log I get "parsererror SyntaxError {}" and "parsererror".

How can I make this right? Below is the code.

JQuery

$(':submit').live('click', function() {

    $.ajax({

            type : 'post',        
            url: 'testJSON.php',
            beforeSend:console.log('sending...'),
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function(data){

                console.log(data.status);
                // do magic
                },

            error: function(XMLHttpRequest, textStatus, errorThrown) {

                console.log(textStatus, errorThrown);

                },

            complete: function(XMLHttpRequest, status) {

                console.log(status);

                }

        });

    return false;
    });

and this is the testJSON.php

<?php

$data = array(

    "status" => 1,
    "firstname" => "foo",
    "lastname" => "bar",

);

header('Content-type: application/json; charset=utf-8" ');
echo json_encode($data);


exit();

?>

FYI I use the latest version of WAMP. Any help very much appreciated.

Set the header of the content to type of json... Here is an example of setting header type.

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

In jQuery 1.4 onwards the JSON data is parsed in a strict manner.

Any malformed JSON is rejected and a parse error is thrown.

remove " from here

header('Content-type: application/json; charset=utf-8" ');

should be

header('Content-type: application/json; charset=utf-8');

I tried your code and I got an error at the beforeSend parameter. The statements shall be encapsulated in a function:

...    
beforeSend: function() {console.log('sending...')},
...

After that everything worked. Maybe it also depends on the jQuery version. Which one did you use? I tried with versions 1.8.1 and upwards

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