Home > Web Front-end > JS Tutorial > body text

4 solutions to Javascript cross-domain requests_javascript skills

WBOY
Release: 2016-05-16 17:40:21
Original
1201 people have browsed it
Under what circumstances does cross-domain occur?
Assume the domain name is: http://www.example.com.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 normal. The cross-domain request method cannot be requested.
Solution:
1. window.name
1. The server returns
Copy code The code is as follows:

<script>window.name='{"id":"3", "name":"leisure"}';&lt ;/script> <br>2. Define an iframe and add onload event<iframe id="iframe1" onload="iLoad"><iframe> <br><script type="text/javascript"> <br>var load = false; <br>function iLoad() { <br>if(load == false) { <br>// Same domain processing, the iframe will be reloaded again after the request <br>document.getElementById( 'iframe1').contentWindow.location = '/'; <br>load = true; <br>} else { <br>// Get the content of window.name. Note that it must be accessed after the same domain processing! <br>var data = document.getElementById('iframe1').contentWindow.name; <br>alert(data); // {"id":"3", "name":"leisure"} <br>load = false; <br>} <br>} <br></script>

3. Define a form, set the form's target to the id of the iframe, and then submit the form
Copy code The code is as follows:



2. JSONP
The server returns callback({"id": "3", "name": "leisure"});
Copy code The code is as follows:



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

$.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 It is actually implemented using JSONP.
4. Flash cross-domain
Add crossdomain.xml to the server
http://www.example.com.cn/crossdomain.xml
Copy code The code is as follows:




Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!