Sending JSON data with jQuery not working

时间:2018-03-23 00:12:26

标签: javascript jquery json

Simple request being made

    var username = {'username' : 'tom'};

    var request = $.ajax({
        url      : 'test.php',
        method   : 'GET',
        data     : JSON.stringify(username),
        dataType : 'json'
    });

    request.done(function(response) {
        response = JSON.parse(response);
        console.log(response);
    });

    request.fail(function(xhr, status, error) {
        console.log(error);
    });

PHP:

<?php
echo json_encode(array("bar" => "bar"));
?>

Still getting error, no idea why

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:4)

that's because the server is returning a non valid JSON string. Try to check what the server is returning. This may happen if your server is throwing an error. In your case, I think the error you are trying to parse is not a JSON string. You might want to check that out as well.
You can use this link to validate your JSON.