简体   繁体   中英

jQuery.getJSON not being called?

This is my code:

$.getJSON('/test.php', {q: value},  function(data, status) {
    if (status !== 'success') {
        console.log('error: ' + status);
        return;
    } else {
        console.log('ok');
    }
});

The test.php looks like this:

echo 'foobar';

I am not getting any error messages but it also seems that the request is not made. Any idea what could be wrong?

Thanks!

What you're sending back ( foobar ) isn't valid JSON, so you're triggering the error handler. But since you haven't listened for errors, you're not seeing anything. The callback you give getJSON is the success callback (see the docs ).

Here's one way you'd handle both success and error:

$.getJSON('/test.php', {q: value})
    .done(function(data) {
        console.log('ok');
    })
    .fail(function(error) {
        console.log('error: ', error);
    });

Here's how you'd send back a valid JSON response:

echo json_encode('foobar');

That outputs the valid JSON

"foobar"

(It used to be that the top level of JSON text had to be an object or an array, but that hasn't been true for years, so just a string is fine.)

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