1. The browser has configured the same origin policy for security. If the protocol, domain name, and port number of two urls are identical, they are of the same origin. If you have different sources it’s cross-domain. We typically use CORS or JSONP to resolve cross-domains.

2.CORS(Cross-domain resource sharing) : Enable access-Control-allow-origin on the server to add urls that you want to cross-domain.

3.JSONP (Informal Cross-domain data Exchange protocol) : Use JSONP when the browser does not support CORS. JSONP fetches data as JS code by loading it with script tags. Declare a function on the page in advance. The function name is passed to the background through the way of interface parameter passing. After the background parses to the function name, it “wraps” the function name on the original data and sends it to the front end. In other words, JSONP requires the coordination of the back end of the corresponding interface.

Advantages:

  1. Compatible with IE;

Disadvantages:

  • Since it is a script tag, there is no way to know what the status code is, only success and failure.
  • Only GET requests can be sent. Post is not supported.
function jsonp(setting){ setting.data = setting.data || {} setting.key = setting.key||'callback' setting.callback = setting.callback||function(){} setting.data[setting.key] = '__onGetData__' window.__onGetData__ = function(data){ setting.callback (data); } var script = document.createElement('script') var query = [] for(var key in setting.data){ query.push( key + '='+ encodeURIComponent(setting.data[key]) ) } script.src = setting.url + '? ' + query.join('&') document.head.appendChild(script) document.head.removeChild(script) } jsonp({ url: 'http://api.jirengu.com/weather.php', callback: function(ret){ console.log(ret) } }) jsonp({ url: 'http://photo.sina.cn/aj/index', key: 'jsoncallback', data: { page: 1, cate: 'recommend' }, callback: function(ret){ console.log(ret) } })Copy the code