Home >Web Front-end >JS Tutorial >Briefly talk about json cross-domain_javascript skills

Briefly talk about json cross-domain_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:10:541533browse

This article is mainly because I have heard others talk about json cross-domain and cross-domain before, but I am still confused and only know one thing. So in a rage, I read through various information and found out if there was anything incorrect. , please correct me^_^

First of all, understand that browsers have a very important security restriction, which is the same-origin policy: client scripts in different domains cannot read each other's resources without explicit authorization. Cross-domain means different sources~

To put it simply, as long as the protocol, port, and domain name are different, it is cross-domain!

However, when doing some in-depth front-end programming, cross-domain operations are inevitably required. At this time, the "same origin policy" appears to be too harsh.

Solution:

1. Use jsonp to solve cross-domain issues: (only for GET requests)

Implementation principle: The 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag is not restricted by the same-origin policy. It can load JavaScript files from anywhere without requiring the same origin.
So the idea of ​​JSONP is that I agree on a function name with the server, and when I request a file, the server returns a piece of JavaScript. This JavaScript calls the function we agreed on and passes data in as parameters. By a very coincidence (not really), the data format of JSON is exactly the same as the format of objects in the JavaScript language. So this object can be used directly in the function we agreed on.

Use JavaScript code to solve

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

Use jquery to solve

 $.ajax({ 
    url: http://跨域的dns/document!searchJSONResult.action, 
    type: "GET", 
    dataType: 'jsonp',   //主要是这里和原来的json改变了!
    jsonp: 'jsoncallback', 
 })

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

window.postMessage(message,targetOrigin) method is a newly introduced feature of HTML5. You can use it to send messages to other window objects, regardless of whether the window object belongs to the same origin or different origins.

--------------------- Let's introduce these two solutions for now... Actually there are many others, I will add them one by one later------------- ----

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn