php + ajax + html 简单跨域问题

XMLHttpRequest cannot load http://localhost:8080/abc/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file:///E:/myprogram/php/abc/index.html' is therefore not allowed access.

我想实现的目标是这样的: 用php写好一个接口,然后html中ajax直接post这个接口,进行json数据的交互。

简化的index.html代码

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <title>php+ajax+html跨域问题</title>
 5 <script src="jquery.js" ></script>
 6 </head>
 7 <body>
 8 <form>
 9     姓名<input type="text" id="uname" /><br/>
10     <input type="button" value="btn" id="btn" />
11 </form>
12 </body>
13 <script>
14     $(function(){
15         $("#btn").click(function(){
16             var uname = $("#uname").val();
17             var serviceUrl = "http://localhost:8080/abc/index.php";
18             var param = {'json':'{"name":"'+uname+'"}'};
19             $.post(serviceUrl,param,function(data){
20                 console.log(data);
21             });
22         });
23     });
24 </script>
25 </html>        

简化的index.php代码

1 <?php
2     if(isset($_POST["json"])){
3         echo $_POST["json"];
4         exit();
5     }
6 ?>

跨域问题的出现

开启apache服务器后,这样访问 file:///D:/abc/index.html 页面,不要http://localhost:8080/abc/index.html 访问,因为这样访问的话,就看不到跨域问题的出现了

当我们在index.html填写好姓名后,点击btn按钮,这时ajxa请求就发送出去了。在chrome的调试模式下,控制台会提示有错误发生,如下

php + ajax + html 简单跨域问题

什么是跨域?

我的理解就是:在A网站域名下去访问B网站下的资源。

目前我使用的chrome(版本 46.0.2471.2)、FireFox(39.0)、Opera(版本30.0.1835.125)都会出现这个跨域问题

解决方法

在html的ajax要请求的服务端php页面中添加下面的一行代码:

header("Access-Control-Allow-Origin:*");

也就是http://localhost:8080/abc/index.php中添加

然后再和上面一样访问一次  file:///D:/abc/index.html ,填写好姓名,点击btn按钮,结果如下

php + ajax + html 简单跨域问题

没有出现跨域的错误提示了!