html之ajax

正常情况下,html中的ajax(也就是XMLHttpRequest对象)是不能跨域的。(特殊情况,此处不讨论,请网上Google)

---跨域:是url的协议或ip或端口,其中有一个不同,就是跨域。

比如:

1 http://10.1.50.45:8080与http://10.1.50.45:8081,

2 或者http://10.1.50.30:8080与http://10.1.50.45:8080,

3 或者https://10.1.50.30:8080与http://10.1.50.45:8080,

4 或者file:///D:/test1.html与http://10.1.50.45:8080。

上述四种情况,是都不会成功的,浏览器都会报错:(是chrome的报错信息)

1 【这是第1 2 3种情况】XMLHttpRequest cannot load http://localhost:3004/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access.

2 【这是第四种情况:file:///】XMLHttpRequest cannot load http://localhost:3004/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

但是!

第4种情况,在node-webkit中,是可以成功的!!仅仅是node-webkit!估计是它做了处理。

代码如下:(请把该文件,放到其他域中测试,如http://localhost:3003/)

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <button onclick="get();">get</button>
        <script>
            function get(){
var xmlhttp=new XMLHttpRequest(); var url="http://localhost:3004/test"; xmlhttp.open("get",url,true); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readystatus==4){ if(xmlhttp.status==200){ } } }; xmlhttp.send(null); } </script> </body> </html>
原文地址:https://www.cnblogs.com/simonbaker/p/3870523.html