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

笔记:

在搭建好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然后就能正常使用了

你可能感兴趣的:(解决js使用ajax访问的跨域问题)