bhagirathi
bhagirathi

Reputation: 531

Get json data from another domain(cross domain)

I am new to jquery and don't know to fetch json data from another domain(Cross domain).

function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    xhr = null;
}
return xhr;
}

var request = createCORSRequest("get", "http://www.stackoverflow.com/");
if (request){
request.onload = function() {
    // ...
};
request.onreadystatechange = handler;
request.send();
}

I found this program from here Ways to circumvent the same-origin policy

This is saying by using above code we can access cross domain json data.

I copied the code. This is saying handler is undefined

I don't know how to define handler .

I also don't know what to write inside request.onload

where I will get the json result

Please help

Thanks in advance

Upvotes: 0

Views: 1065

Answers (1)

Praneeta
Praneeta

Reputation: 1594

The handler is a function

it should be something like

function handler(){
   var response = xhr.responseText;
   // do more with your response.
}

Also you xhr should be defined outside of the function createCORSrequest.

See docs on XDR

I know you said you are new to jquery but you should also look into $.getJSON. Its much easier.

Upvotes: 2

Related Questions