开发者

jquery getJSON from local socket

I am having trouble with the json.getJSON method. Here is my current code:

var jqxhr = $.getJSON("http://127.0.0.1:5002?callback=?", function() {
                alert("success");
            })
            .success(function() { alert("second success"); })
            .error(function() { alert("error"); })
            .complete(function() { alert("complete"); });

It is almost exactly like the example from the jquery documentation. However, I never hit the callback function (alert("success")). I always end up receiving the error alert. With the empty callback on the URL I am using, I can see a successful JSON GET method in FireBug and FireBug renders the JSON perfectly. Without the callback in that URL, I do not see the JSON in Firebug. However, when I hit http://127.0.0.1:5开发者_开发技巧002 directly with firefox, the JSON appears just fine.

Here is the JSON:

{"AllData":[{"dataName":"TestData","data":[0,0,0],"color":"Green"}]}

I have tried both with and without the callback on the URL with MIME types application/json, application/javascript, application/x-json, application/x-javascript, text/javascript, and text/plain but cannot receive a "success" alert from the .getJSON.

This JSON parses just fine with jquery.parseJSON and even works perfectly when I use .getJSON and pull the JSON from a .js file.

Any suggestions? Is reading JSON from a socket with .getJSON even possible?


You're adding ?callback=? which turns this into a JSONP request. When echoing the JSON, you need to wrap it in the callback function passed to the server.

So, instead of outputting just JSON:

{"AllData":[{"dataName":"TestData","data":[0,0,0],"color":"Green"}]}

You need to output JSONP:

cFunc({"AllData":[{"dataName":"TestData","data":[0,0,0],"color":"Green"}]});

Replace cFunc with the value of the callback GET parameter ($_GET['callback'] in PHP, for example). jQuery will send a name for a callback function when it does the XHR request, this name will be a reference to the callback passed to $.getJSON.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜