简体   繁体   English

jQuery.getJSON没有被调用?

[英]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: test.php看起来像这样:

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. 您发回的内容( foobar )是无效的JSON,因此您正在触发错误处理程序。 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 ). 您给getJSON的回调是success回调(请参阅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: 这是发送回有效JSON响应的方法:

echo json_encode('foobar');

That outputs the valid JSON 输出有效的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.) (过去,JSON文本的顶层必须是一个对象或数组,但是多年以来一直不是这样,所以只用一个字符串就可以了。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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