Jquery gives error on valid, properly labeled JSON data? [duplicate]
Possible Duplicate:
Cross Domain Limitations With Ajax - JSON
I am using the following method to attempt to get json (I have it happening two ways just to see what's going on. Disabling either way and just running one or the other gets me the same errors).
var jqxhr = $.getJSON("http://exampleurl/stats.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function(data) { console.log(data); })
$.ajax({
url: "http://exampleurl/stats.json",
dataType: 'text json',
cache: false,
success: test
});
When I run it, I get the standard 200 ok, but with an error. (And no explanation for it, the object just has a statusText of "error").
The JSON I'm getting back (via tcpdump and wireshark) looks like:
HTTP/1.1 200 OK
Content-type: application/json
Content-length: 341
{"perIPUsage": [{ "10secWindow": { "bitsPerSecond": 904956.8, "bytes": 1131196, "seconds": 10 }, "2secWindow": { "bitsPerSecond": 867056, "bytes": 216764, "seconds": 2 },开发者_运维技巧 "60secWindow": { "bitsPerSecond": 984093.8666666667, "bytes": 7380704, "seconds": 60 }, "address": "0:0:0:0:0:0:0:1" }]}
Which JsonLint says is perfectly valid (AND you'll notice that the content-type is set correctly).
I'm calling out to an external address, so I can't just do it relative (which i've heard fixes it for some people).
What am I doing wrong? Why does it keep thinking my valid json is wrong?
You're using dataType "text json", which will attempt to convert text into JSON. But you're not getting text; you're getting application/json
. So just use dataType "json" and see what happens.
dataType is used to specify the type of return data
dataType: 'text/html',
OR
dataType: 'json',
There is a built-in restriction called Same Origin Policy to prevent cross-domain Ajax requests from the browser. Pretty much all browsers implement this, and it's a good thing.
There are workarounds such as the article here or using JSONP. But this is a basic restriction put on Ajax requests sent from the browser.
See also: Cross Domain Limitations With Ajax - JSON
精彩评论