代码区项目交易流程

Cross-domain query in JavaScript vs. jQuery's JSONP


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!

Cross origin XHR requests have to be allowed by the server using Access-Control-Allow-Origin . JSONP is a mechanism to work around it.

This wiki page contains very good description of why it works. See the Script element injection section.

https://en.wikipedia.org/wiki/JSONP

This stackoverflow answer shows how to use pure javascript to make jsonp calls.

Can anyone explain what JSONP is, in layman terms?

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

点击收藏

LAST 关于高效、高质和高产 巧用这19条MySQL优化,效率至少提高3倍 NEXT