Home  >  Article  >  Web Front-end  >  Detailed explanation of how to implement Javascript cross-domain request code

Detailed explanation of how to implement Javascript cross-domain request code

伊谢尔伦
伊谢尔伦Original
2017-07-20 11:39:221499browse

Under what circumstances will cross-domain occur?

Assume that the domain name is: http://www.php.cn
If the requested domain name is different from this domain name, this situation is cross-domain. Since there are loopholes in cross-domain, it is generally For example, normal cross-domain request methods cannot be requested.
Solution:
1. window.name
1. The server returns

<script>window.name=&#39;{"id":"3", "name":"leisure"}&#39;;</script>

2. Define an iframe and add the onload event< ;iframe id="iframe1" onload="iLoad">d5ba1642137c3f32f4f4493ae923989c

<script type="text/javascript"> 
var load = false; 
function iLoad() { 
if(load == false) { 
// 同域处理,请求后会再次重新加载iframe 
document.getElementById(&#39;iframe1&#39;).contentWindow.location = &#39;/&#39;; 
load = true; 
} else { 
// 获取window.name的内容,注意必须进行同域处理后方可访问! 
var data = document.getElementById(&#39;iframe1&#39;).contentWindow.name; 
alert(data); // {"id":"3", "name":"leisure"} 
load = false; 
} 
} 
</script>

3. Define a form, set the form's target to the iframe's id, and then submit the form

<form action="url" method="POST" target="iframe1"> 
<button type="submit" value="submit" /> 
</form>


2. JSONP
The server returns callback({"id": "3", "name": "leisure" });

<script type="text/javascript"> 
function callback(data) { 
alert(data); 
} 
</script> 
<script type="text/javascript" src="http://www.php.cn/product.jsp?id=5&jsonp=callback"></script>


3. jQuery.getJSON
The server returns json format data test({"id": "3", "name": "leisure" }); The test function name is defined in the callback parameter

$.getJSON(url + "?callback=?", data, function(data) { 
}

Note that the callback=? parameter must be brought, jquery will automatically generate a function name to replace the question mark! jQuery.getJSON is actually implemented using JSONP.

4. Flash cross-domain
Add crossdomain.xml to the server
http://www.php.cn/ crossdomain.xml

<?xml version="1.0"?> 
<cross-domain-policy> 
<allow-access-from domain="*.another.com.cn" /> 
</cross-domain-policy>


The above is the detailed content of Detailed explanation of how to implement Javascript cross-domain request code. For more information, please follow other related articles on the PHP Chinese website!

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