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='{"id":"3", "name":"leisure"}';</script>
2. Define an iframe and add the onload event< ;iframe id="iframe1" onload="iLoad">
<script type="text/javascript"> var load = false; function iLoad() { if(load == false) { // 同域处理,请求后会再次重新加载iframe document.getElementById('iframe1').contentWindow.location = '/'; load = true; } else { // 获取window.name的内容,注意必须进行同域处理后方可访问! var data = document.getElementById('iframe1').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!