Under what circumstances will CORS occur?
Assume the domain name is: http://www.example.com.cn/
If the requested domain name does not match this domain name, this is a cross-origin scenario. Due to a cross-origin vulnerability, normal cross-origin request methods cannot be requested.
Solution:
1. window. name
1. The server returns
Copy codeThe Code is as follows: <script> window. name = '{"id": "3", "name": "leisure"}'; </script>
2. Define an iframe and add an onload event <iframe id = "iframe1" onload = "iLoad"> <iframe>
<Script type = "text/javascript">
Var load = false;
Function iLoad (){
If (load = false ){
// If the request is processed in the same domain, the iframe will be reloaded again.
Document. getElementById ('iframe1'). contentWindow. location = '/';
Load = true;
} Else {
// Obtain the content of window. name. Note that it must be processed in the same domain before access!
Var data = document. getElementById ('iframe1'). contentWindow. name;
Alert (data); // {"id": "3", "name": "leisure "}
Load = false;
}
}
</Script>
3. Define a form, set the target of the form to the id of iframe, and then submit the formCopy codeThe Code is as follows: <form action = "url" method = "POST" target = "iframe1">
<Button type = "submit" value = "submit"/>
</Form>
Ii. JSONP
The server returns callback ({"id": "3", "name": "leisure "});Copy codeThe Code is as follows: <script type = "text/javascript">
Function callback (data ){
Alert (data );
}
</Script>
<Script type = "text/javascript" src = "http://www.example.com.cn/product.jsp? Id = 5 & jsonp = callback "> </script>
Iii. jQuery. getJSON
The server returns data in json format test ({"id": "3", "name": "leisure"}); the test function name is defined in the callback parameter.Copy codeThe Code is as follows: $. getJSON (url + "? Callback =? ", Data, function (data ){
}
Note callback =? This parameter must be included. jquery will automatically generate a function name to replace this question mark! JQuery. getJSON is actually implemented using the JSONP method.
Iv. flash cross-Origin
Add crossdomain. xml to the server
Http://www.example.com.cn/crossdomain.xmlCopy codeThe Code is as follows: <? Xml version = "1.0"?>
<Cross-domain-policy>
<Allow-access-from domain = "* .another.com.cn"/>
</Cross-domain-policy>