您的位置:首页 > Web前端 > JavaScript

解决js使用ajax访问的跨域问题

2016-09-15 14:06 676 查看
笔记:

在搭建好nginx和php后急忙测试了一个简单的页面,其中使用了ajax访问服务器

$.post('http://localhost:82/forumObject/check_name.php', {
uname: unameValue
}, function(data) {
document.write(data);
}, 'html');
});

返回不是json所以没用jsonp,可是存在跨域的问题,提示我

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

解决办法就是在被请求的服务端页面添加header

header('content-type:application:json;charset=utf8');  

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

header('Access-Control-Allow-Methods:POST');  

header('Access-Control-Allow-Methods:GET');

header('Access-Control-Allow-Headers:x-requested-with,content-type'); 

加上这些header然后就能正常使用了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: