简体   繁体   中英

Converting array to JSON to check the values

I send an Ajax call to a PHP file, Then an array is returned.

I want to check the values of the returned data.

Here is the Javascript/jQuery code:

$.ajax({
    url: "file.php",
    type: "POST",
    data: {'num': 12},
    dataType : "json",
    success: function(data){
        JSON.parse(data);
        console.log(data.status);
    }
});

PHP code:

$status = 1;
$msg = 'Test message';
$response = array($status, $msg);
echo json_encode($response);

But I'm getting an error JSON.parse: unexpected non-whitespace character

You used dataType: "json", in the AJAX parameter list, which tells jQuery to expect JSON and do the Parse internally for you.

So remove the JSON.parse(data); and all should be well

You will also have to change the PHP to make the returned data appear in the right place like this

$response = array('status' => $status, 'message' => $msg);

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