在jQuery中使用getJSON函数时,回调函数不起作用

时间:2022-04-05 12:57:05

I am trying to use the getJSON function in jQuery to import some data and trigger a callback function. The callback function doesn't run. However, if I try the same thing with the get function, it works fine. Strangely, it works with the get function even when I pass "json" as the type. Why is this happening? I tested the following file in Firefox 3 and IE 7:

我正在尝试使用jQuery中的getJSON函数来导入一些数据并触发回调函数。回调函数不会运行。但是,如果我对get函数做同样的尝试,它会很好地工作。奇怪的是,即使我将“json”作为类型传递,它也与get函数一起工作。为什么会这样?我在firefox3和ie7中测试了以下文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>ajax test</title>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
</head>
<body>
<input type="button" id="test1" value="get">
<input type="button" id="test2" value="getJSON">
<input type="button" id="test3" value="get with json type">
<script type="text/javascript">
$("#test1").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        }
    )
});

$("#test2").click(function() {
    $.getJSON("index.html",
        function(response) {
            alert('hi');
            //doesn't work
        }
    )
});

$("#test3").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        },
        "json"
    )
});
</script>
</body></html>

This seems to happen no matter what URL I access, as long as it's on the same domain. I tried passing some data and that doesn't make a difference.

无论我访问什么URL,只要它在相同的域中,这似乎都会发生。我试着传递一些数据,这没有什么区别。

Of course I can work around the problem by using the get function like I did in my 3rd test function, but I am still curious as to why this is happening.

当然,我可以使用get函数来解决这个问题,就像我在第三个测试函数中做的那样,但是我仍然很好奇为什么会发生这种情况。

I know there is a similar question asked here but it didn't answer my question.

我知道这里有一个类似的问题,但它没有回答我的问题。

8 个解决方案

#1


24  

The json needs to be valid, otherwise the callback will not fire.

json必须有效,否则回调不会触发。

#2


4  

$.getJSON() is JSONP, so change it this way:

$.getJSON()是JSONP,因此可以这样更改:

$("#test2").click(function() {
    $.getJSON("index.html?callback=?",
        function(response) {
                alert('hi');
        }
    )
});

Server receives param callback filled with something like: jsonp1291077863309. In a response write back callback function jsonp1291077863309( PUT_JSON_HERE).

服务器接收由以下内容填充的param回调:jsonp1291077863309。在响应回写回调函数jsonp1291077863309(PUT_JSON_HERE)中。

#3


3  

Right! After 2 days getting crazy trying to make $.getJSON to accept a well-formed JSon string from the server, the problem was really on the server! Just like Carl_Platt says, you have to prepend the callback value received as a url parameter to the json output ($_GET['callback'] in PHP). That's called "JSON-P output", just in case you want to google about it.

没错!在两天的时间里疯狂的想要赚到钱。要接受来自服务器的格式良好的JSon字符串,问题实际上是在服务器上!就像Carl_Platt说的那样,您必须将作为url参数接收的回调值前置到json输出(PHP中的$_GET['callback'])。这叫做“JSON-P输出”,以防您想要谷歌。

Hands on, here a page where they show the solution in PHP:

这里有一个页面展示了PHP的解决方案:

http://1080d.com/lang/en-us/2009/10/converting-php-to-jsonp-with-json_encode/

http://1080d.com/lang/en-us/2009/10/converting-php-to-jsonp-with-json_encode/

And remember (really important) to add to the url you call the callback=? parameter! (Only needed if the url you are calling is not in the same server serving the executing jquery script)...

还记得(非常重要)要添加到您调用callback=的url吗?参数!(只有当您正在调用的url不在服务于正在执行的jquery脚本的同一服务器上时才需要)……

JQuery will automatically replace '?' with a convenient value before sending it to the server. You don't need to worry about which value is used, it will all be seamless for you (if the server makes the right job! And that was the problem in my case!) :-)

JQuery会自动取代'?在发送给服务器之前,要有一个方便的值。您不需要担心使用了哪个值,这对您来说都是无缝的(如果服务器做了正确的工作!)这就是我的问题所在!

Hope it helps!

希望它可以帮助!

#4


0  

Under the surface, when you call getJSON, this is what's happening:

在表面之下,当您调用getJSON时,会发生以下情况:

// ~ line 3216
getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
}, // ... rest of jQuery core

So there must be some other thing preventing the callback from firing...

所以一定还有别的东西阻止回调触发……

I would start by **alert**ing different things (not just 'hi') on each callback, that way you know which one is failing/succeeding.

我将从每次回调中提醒不同的事情(而不仅仅是“嗨”)开始,这样您就知道哪个正在失败/成功。

#5


0  

As mentioned by numerous others, you need valid JSON (i.e. complies with the rules at http://json.org/) for getJSON to work (this means you cannot get HTML via getJSON as in your example).

正如许多其他人提到的,要让getJSON工作,您需要有效的JSON(即遵守http://json.org/上的规则)(这意味着您不能像示例中那样通过getJSON获得HTML)。

The reason the last test works is because the last parameter "json" is not being interpreted as the "type". Because the following does NOT work:

最后一个测试成功的原因是最后一个参数“json”没有被解释为“类型”。因为以下方法不起作用:

$("#test3").click(function() {
    $.get("index.html",
        '',
        function(response) {
                alert('hi');
                //works
        },
        "json"
    )
});

#6


0  

I had the same issue despite having well formed JSON etc. I was able to query my webservice, and get a response, however, my callback function wasn't firing. After scrounging the net, i most interwebers suggested using 'jsonp', which i did since my app performs some cross domain calls, and also added 'callback?' to my url. This didn't work but that including the callback with the returned JSON solved my problem. The code below explains what i mean:

尽管我有很好的JSON格式,但我还是遇到了同样的问题。我可以查询我的webservice,得到一个响应,但是我的回调函数没有被触发。在搜索了网络之后,大多数网友都建议我使用“jsonp”,因为我的应用程序执行了一些跨域调用,还添加了“callback?”“我的url。这没有起作用,但是包含返回的JSON的回调解决了我的问题。下面的代码解释了我的意思:

//server side json formed somewhere up here
String data = callback + "("+ json +")" ;

the response resulting from this is something like "jsonp1280403476086([{"Name":"Jack Sparrow" which jQuery seemed to not have a problem and so never died on me.

由此产生的响应是“jsonp1280403476086”([{"Name":"Jack Sparrow"), jQuery似乎没有问题,所以从来没有死在我身上。

Hope this helps.

希望这个有帮助。

#7


0  

Use $.post instead of $.getJSON(), in MVC2 if you are using $.getJSON or $.get be sure to set JsonRequestBehavior to AllowGet. Else this will return HTML error that causes your requst not to trigger the callback.

使用美元。在MVC2中,如果使用$. getjson()而不是$. getjson()。getJSON或美元。确保将JsonRequestBehavior设置为AllowGet。否则将返回HTML错误,导致requst不触发回调。

#8


0  

Make sure you don't have [HttpPost] listed above your JsonResult method in your controller. This will not return data to a .getJSON call.

请确保在控制器中没有在JsonResult方法上列出[HttpPost]。这不会将数据返回给. getjson调用。

#1


24  

The json needs to be valid, otherwise the callback will not fire.

json必须有效,否则回调不会触发。

#2


4  

$.getJSON() is JSONP, so change it this way:

$.getJSON()是JSONP,因此可以这样更改:

$("#test2").click(function() {
    $.getJSON("index.html?callback=?",
        function(response) {
                alert('hi');
        }
    )
});

Server receives param callback filled with something like: jsonp1291077863309. In a response write back callback function jsonp1291077863309( PUT_JSON_HERE).

服务器接收由以下内容填充的param回调:jsonp1291077863309。在响应回写回调函数jsonp1291077863309(PUT_JSON_HERE)中。

#3


3  

Right! After 2 days getting crazy trying to make $.getJSON to accept a well-formed JSon string from the server, the problem was really on the server! Just like Carl_Platt says, you have to prepend the callback value received as a url parameter to the json output ($_GET['callback'] in PHP). That's called "JSON-P output", just in case you want to google about it.

没错!在两天的时间里疯狂的想要赚到钱。要接受来自服务器的格式良好的JSon字符串,问题实际上是在服务器上!就像Carl_Platt说的那样,您必须将作为url参数接收的回调值前置到json输出(PHP中的$_GET['callback'])。这叫做“JSON-P输出”,以防您想要谷歌。

Hands on, here a page where they show the solution in PHP:

这里有一个页面展示了PHP的解决方案:

http://1080d.com/lang/en-us/2009/10/converting-php-to-jsonp-with-json_encode/

http://1080d.com/lang/en-us/2009/10/converting-php-to-jsonp-with-json_encode/

And remember (really important) to add to the url you call the callback=? parameter! (Only needed if the url you are calling is not in the same server serving the executing jquery script)...

还记得(非常重要)要添加到您调用callback=的url吗?参数!(只有当您正在调用的url不在服务于正在执行的jquery脚本的同一服务器上时才需要)……

JQuery will automatically replace '?' with a convenient value before sending it to the server. You don't need to worry about which value is used, it will all be seamless for you (if the server makes the right job! And that was the problem in my case!) :-)

JQuery会自动取代'?在发送给服务器之前,要有一个方便的值。您不需要担心使用了哪个值,这对您来说都是无缝的(如果服务器做了正确的工作!)这就是我的问题所在!

Hope it helps!

希望它可以帮助!

#4


0  

Under the surface, when you call getJSON, this is what's happening:

在表面之下,当您调用getJSON时,会发生以下情况:

// ~ line 3216
getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
}, // ... rest of jQuery core

So there must be some other thing preventing the callback from firing...

所以一定还有别的东西阻止回调触发……

I would start by **alert**ing different things (not just 'hi') on each callback, that way you know which one is failing/succeeding.

我将从每次回调中提醒不同的事情(而不仅仅是“嗨”)开始,这样您就知道哪个正在失败/成功。

#5


0  

As mentioned by numerous others, you need valid JSON (i.e. complies with the rules at http://json.org/) for getJSON to work (this means you cannot get HTML via getJSON as in your example).

正如许多其他人提到的,要让getJSON工作,您需要有效的JSON(即遵守http://json.org/上的规则)(这意味着您不能像示例中那样通过getJSON获得HTML)。

The reason the last test works is because the last parameter "json" is not being interpreted as the "type". Because the following does NOT work:

最后一个测试成功的原因是最后一个参数“json”没有被解释为“类型”。因为以下方法不起作用:

$("#test3").click(function() {
    $.get("index.html",
        '',
        function(response) {
                alert('hi');
                //works
        },
        "json"
    )
});

#6


0  

I had the same issue despite having well formed JSON etc. I was able to query my webservice, and get a response, however, my callback function wasn't firing. After scrounging the net, i most interwebers suggested using 'jsonp', which i did since my app performs some cross domain calls, and also added 'callback?' to my url. This didn't work but that including the callback with the returned JSON solved my problem. The code below explains what i mean:

尽管我有很好的JSON格式,但我还是遇到了同样的问题。我可以查询我的webservice,得到一个响应,但是我的回调函数没有被触发。在搜索了网络之后,大多数网友都建议我使用“jsonp”,因为我的应用程序执行了一些跨域调用,还添加了“callback?”“我的url。这没有起作用,但是包含返回的JSON的回调解决了我的问题。下面的代码解释了我的意思:

//server side json formed somewhere up here
String data = callback + "("+ json +")" ;

the response resulting from this is something like "jsonp1280403476086([{"Name":"Jack Sparrow" which jQuery seemed to not have a problem and so never died on me.

由此产生的响应是“jsonp1280403476086”([{"Name":"Jack Sparrow"), jQuery似乎没有问题,所以从来没有死在我身上。

Hope this helps.

希望这个有帮助。

#7


0  

Use $.post instead of $.getJSON(), in MVC2 if you are using $.getJSON or $.get be sure to set JsonRequestBehavior to AllowGet. Else this will return HTML error that causes your requst not to trigger the callback.

使用美元。在MVC2中,如果使用$. getjson()而不是$. getjson()。getJSON或美元。确保将JsonRequestBehavior设置为AllowGet。否则将返回HTML错误,导致requst不触发回调。

#8


0  

Make sure you don't have [HttpPost] listed above your JsonResult method in your controller. This will not return data to a .getJSON call.

请确保在控制器中没有在JsonResult方法上列出[HttpPost]。这不会将数据返回给. getjson调用。