I was trying to write a cross domain request (e.g., Google Finance resource) in JavaScript from client-side (the browser) by following a template like below mentioned here:
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 {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var url = 'http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOGL';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var jsonReturend = JSON.parse(text);
console.log(jsonReturend)
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
But it doesn't work because (I think) 'finance.google.com' doesn't include Access-Control-Allow-Origin:
in its response headers, which is understandable. However, I tried another suggested method on StackOverflow post here to use JSONP as follows:
$.ajax({
url: 'http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOGL',
jsonp: "callback",
dataType: "jsonp",
data: {},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
and it works (that is, I got the expected JSON back)! As a newbie to web development and JS in general, I am not sure why AJAX call via jQuery's JSONP is working whereas it fails in pure JavaScript. My questions are:
- What is JSONP doing differently to make things work? Or is it simply because 'finance.google.com' is allowing JSONP type requests (but not CORS type requests)?
- Is it possible to make it work by strictly using JavaScript? If so, how could I achieve that?
Thank you all for your answers!