Because of security restrictions (homology policy, where JavaScript or cookies can only access content under the same domain), two scenarios for Ajax Cross-domain requests
Scenario One: Jsonp (JSON with Padding)
But one drawback of JSONP is that it does not support get passes
Scenario Two: CORS (cross-domain resource sharing, cross-origin Resource sharing)
This scenario supports post submission
Let's say that we are in HTTP://WWW.A domain name, COM domain name Ajax request http://www.111cn.net domain name under the data, if using Cors to implement, Ajax Cross-domain request.
Just in the http://www.111cn.net domain to be added in the requested PHP script header
Header ("ACCESS-CONTROL-ALLOW-ORIGIN:HTTP://WWW.A domain name. com");
Allow HTTP://WWW.A domain name. com cross domain access to http://www.111cn.net domain
Code instance:
[index.html file under HTTP://WWW.A domain name. com domain name]
| The code is as follows |
Copy Code |
|
<!--This domain name is under HTTP://WWW.A domain name. com Domain name-->
<title>core-ajax cross-Domain </title>
<meta charset= "Utf-8"/>
<script src= "Http://gongwen.sinaapp.com/Public/Js/jquery-1.7.2.min.js" ></script>
<body>
<script type= "Text/javascript" >
$ (function () {
var url= ' http://www.111cn.net/server.php ';
$.post (url,{name: ' Gong Wen ', blog: ' www.bestphper.cn '},function (data) {
var info=eval (' (' +data+ ') ');
$ (' body '). HTML (' name: ' +info.name+ ' <br>blog: ' +info.blog+ ' <br>from: ' +info.from ');
});
});
</script>
</body>
|
[server.php file under http://www.111cn.net domain name]
| The code is as follows |
Copy Code |
|
<?php
Note This file is under the Http://www.111cn.net domain name
Header ("ACCESS-CONTROL-ALLOW-ORIGIN:HTTP://WWW.A domain name. com");
$arr =array (
' Name ' =>$_post[' name ',
' Blog ' =>$_post[' blog '],
' From ' => ' http://www.111cn.net '
);
echo Json_encode ($arr);
|
[Firefox browser access http://www.a domain name. com]
So the question is, how do you use Cors to solve this Ajax cross-domain problem?
As long as the http://www.111cn.net domain name under the server.php file in the
Header ("ACCESS-CONTROL-ALLOW-ORIGIN:HTTP://WWW.A domain name. com");
Note is removed. Remove and then use the browser to access the HTTP://WWW.A domain name. com
Other
If you put the PHP file
Header ("access-control-allow-origin:*"); In this case, the task is a domain can go to Ajax request this file