您的位置:首页 > 编程语言 > PHP开发

php + ajax + html 跨域问题

2015-08-10 12:10 676 查看
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数据的交互。

我只要json,不要说什么jsonp。

简化的index.html代码

<!DOCTYPE html>
<html>
<head>
<title>php+ajax+html跨域问题</title>
<script src="jquery.js" ></script>
</head>
<body>
<form>
姓名<input type="text" id="uname" /><br/>
<input type="button" value="btn" id="btn" />
</form>
</body>
<script>
$(function(){
$("#btn").click(function(){
var uname = $("#uname").val();
var serviceUrl = "http://localhost:8080/abc/index.php";
var param = {'json':'{"name":"'+uname+'"}'};
$.post(serviceUrl,param,function(data){
console.log(data);
},"json");
});
});
</script>
</html>


简化的index.php代码

<?php

// 对json字符串解码,变成数组
$json_arr = json_decode($_POST['json'],true);

//对json_arr数组进行处理

echo json_encode($json_arr);

?>


跨域问题的出现

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

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



什么是跨域?

我的理解就是:在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按钮,结果如下



没有出现跨域的错误提示了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: