Search code examples
javascriptjqueryajaxjsongetjson

Getting JSON to work in IE


I'm having trouble getting data from a JSON feed in IE.

Here's the test. It alerts in FF, Chrome, Safari, but not IE:

function do_something(data){
    alert(data);
}

$(document).ready(function() {
    $.getJSON('https://www.mec.ca/api/v1/stores/1', do_something);
});

​ And here's the fiddle: http://jsfiddle.net/upksp/

I have tried the following solutions to seemingly-related questions with no luck:

I can't help but think it may be a problem with the headers, but don't know enough about them to diagnose. I've successfully used JSONP on the same page with no issues, and I don't see any conflicts. Help!


Note: For the code I'm working on, the API will be on the same domain(1) as the script that is requesting it. However for testing, they will have different subdomains(2) such as www.domain.com vs environment.domain.com. I assume (2) will be problematic, but (1) will work fine?


Solution

  • Due to browser security reasons, you cannot make requests from one origin to another (ex. jsfiddle.net to www.mec.ca). In recent years, browsers have started to circumvent this using CORS (Cross-Origin Resource Sharing). This allows browsers to make requests to another domain, as long as that server (www.mec.ca) is configured to accept them. You can check for this in the response header. For your url (https://www.mec.ca/api/v1/stores/1), CORS is enabled. You can see this in the response header on the line that says. Access-Control-Allow-Origin: *. This means requests are allowed from any domain (*)

    HTTP/1.1 200 OK
    Date: Sat, 24 Nov 2012 01:19:23 GMT
    Server: Apache
    Content-Language: en
    Access-Control-Allow-Origin: *
    X-Powered-By: Servlet/2.5 JSP/2.1
    Vary: Accept-Encoding,User-Agent
    Transfer-Encoding: chunked
    Content-Type: application/json
    

    Because IE has lagged behind in implementing the CORS standard, it was not added to IE until IE10. Therefore, your fiddle will not work in previous versions of IE.