A brief word about json cross domain

  • 2021-01-25 07:09:29
  • OfStack

This 1 article, is mainly before 1 straight listen to others talk about json cross domain cross domain, but still a head of fog, only know its 1, so 1 anger, browse all kinds of information, if there is incorrect place, please bother to correct 1 ^_^

First, understand that browsers have an important security restriction, the same-origin policy: client scripts from different domains cannot read resources from each other without explicit authorization. Cross-domain means different sources

Simply put, as long as the protocol, port, domain name has 1 different, that is cross-domain!

However, when you do some deep front-end programming that inevitably requires cross-domain operations, the same-origin policy can be too harsh.

Solution:

1. Cross-domain resolution using jsonp :(only for GET requests)

Implementation Principle: < script > The tag is not subject to the same origin policy and can be loaded into JavaScript files anywhere without requiring the same origin.
So the idea of JSONP is that I agree with the server to name a function, and when I request a file, the server returns a segment of JavaScript. This section of JavaScript calls our agreed function and passes in the data as an argument. Coincidentally, the data format of JSON is exactly the same as the object format of JavaScript. So we can use this object directly in our convention function.

Use JavaScript code


  var eleScript = document.createElement("script"); 
  eleScript.type = "text/javascript"; 
  eleScript.src = "http://example2.com/getinfo.php"; 
  document.getElementsByTagName("HEAD")[0].appendChild(eleScript);

Use jquery


 $.ajax({ 
    url: http:// cross-domain dns/document!searchJSONResult.action, 
    type: "GET", 
    dataType: 'jsonp',   // Mainly here and the old one json Changed! 
    jsonp: 'jsoncallback', 
 })

2. Use window.postMessage method of HTML5 to transfer data across domains (only compatible with IE8+, FireFox, Chrome, Opera and other browsers)

window.postMessage(message,targetOrigin) method is a new feature introduced in html5. It can be used to send messages to other window objects, whether the window object is of the same origin or a different source.

------------ To introduce these two solutions for the moment... In fact, there are many others, after 11 to add -----------------


Related articles: