0

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?

Community
  • 1
  • 1
J.R.
  • 5,789
  • 11
  • 55
  • 78
  • By an external address, do you mean to a domain that is different from where you're initiating the AJAX call? You cannot call out to another domain using AJAX as that violates the same-origin policy. – Vivin Paliath Oct 07 '11 at 19:49

3 Answers3

0

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.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
0

dataType is used to specify the type of return data

  dataType: 'text/html',

OR

dataType: 'json',
Vikas Naranje
  • 2,350
  • 5
  • 30
  • 40
0

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

Community
  • 1
  • 1
vzwick
  • 11,008
  • 5
  • 43
  • 63