有关同源策略与跨域

众所周知,XMLHttpRequest是严格遵守同源策略的,不被允许访问不同域的资源,但实际上这里的不允许访问不同域的资源,只是请求发过去之后收不到响应信息,但是请求是可以发送成功的。

在192.168.1.190上有如下代码:

1 <?php
2 $name=$_REQUEST['name'];
3 $pass=$_REQUEST['pass'];
4 $fp=fopen('ajax.txt','a+');
5 fwrite($fp,$name.":".$pass."
");
6 ?>

在192.168.1.159上有如下HTML:

 1 <!doctype html>
 2 <html>
 3 <head>
 4 </head>
 5 <body>
 6 <script>
 7 var xmlhttp=new XMLHttpRequest();
 8 var url="http://192.168.1.190/mycode/ajax.php?&name=ajax&pass=ajax";
 9 if(xmlhttp!=null)
10 {
11   xmlhttp.onreadystatechange=state_change;
12   xmlhttp.open("GET",url,true);
13   xmlhttp.send(null);
14 }
15 else
16 {
17   alert("Does not support XMLHTTP");
18 }
19 function state_change()
20 {
21   if(xmlhttp.readyState==4)
22   {    
23     if(xmlhttp.status==200)
24     {
25        alert("OK,get response");
26     }
27     else
28     {
29        alert("problem retrieving data "+xmlhttp.statusText);
30     }
31   }
32 }
33 </script> 
34 </body>
35 </html>

然后访问这个html文件,得到结果如下:

显示收不到响应,但实际上在ajax.txt中已经写入了内容了

原文地址:https://www.cnblogs.com/debugzer0/p/4900988.html