mnsth
mnsth

Reputation: 2287

XMLHttpRequest() JSON throws a network error but similar jQuery .getJSON code works

I have a JSON script loaded from an external website. In its simplest form, the code has been like this (and working):

jQuery.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?",
    function(data){
        document.querySelector("output").textContent = data.postal_codes[0].city;
    });

However, the website owner don't want jQuery if it's not crucial, so I recoded .getJSON to the request = new XMLHttpRequest(); model:

request = new XMLHttpRequest();
request.open("GET", "http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?", true);
request.onload = function() {
    var data = JSON.parse(request.responseText);
    document.querySelector("output").textContent = data.postal_codes[0].city; 
};
request.onerror = function() { /* this gets called every time */ };

I've modified my code many times, read documentations over and over again, yet the .onerror function is the only one always displaying. This is the console:

Errors in IE11 console

Which in Norwegian says that this script requested CORS, that it can't find the origin in the head of Access-Control-Allow-Origin, and that the XMLHttpRequest had a network error, and says "no access".

There could be several reasons as to why this occurs:

1: There's something wrong with the new code

2: There's something in the .getJSON jQuery function (a hack?) that prevents the error from happening

3: There's something crucial in the new code that I have forgot adding

4: There's something with my browser (IE 11 at the moment)

5: Something else?

It would be lovely with some help on this.

DEMO: http://jsbin.com/muxigulegi/1/

Upvotes: 0

Views: 2975

Answers (2)

sebnukem
sebnukem

Reputation: 8333

From http://api.jquery.com/jquery.getjson/:

JSONP

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

You do have a callback. Which means that the JQuery function can request data from another domain, unlike your XHR call.

Upvotes: 0

Quentin
Quentin

Reputation: 944455

That isn't a network error. It's a cross origin error. The request is successful but the browser is denying access to the response to your JavaScript.

Since you have callback=? in the URL, jQuery will generate a JSONP request instead of an XMLHttpRequest request. This executes the response as a script instead of reading the raw data.

You are manually creating an XMLHttpRequest, so it fails due to the Same Origin Policy.

Create a JSONP request instead.

Upvotes: 5

Related Questions