saber 酱的抱枕

Fly me to the moon

04/20
2016
学习

使用Access-Control-Allow-Origin解决Ajax跨域问题

跨域问题是web开发中一个常见的问题。例如说从网站a.com上用ajax把一些信息发送到b.com上,就会产生跨域问题。浏览器为了安全会阻止这个跨域请求,并产生一个跨域错误。

如果接收方b.com对应的文件是php文件,则可以在header函数中指定Access-Control-Allow-Origin的值,来设置哪些域名可以向这里发送跨域请求。

示例:

ajax请求如下(本彩笔使用了jq的ajax):

$.ajax({
    url:"http://127.0.0.1/t/t.php",
    type:"get",
    async:true,
    cache:false,
    dataType:"text",
    success:function  (data) {
        alert(data);
    }
});

php文件添加Access-Control-Allow-Origin头:

header("Access-Control-Allow-Origin:*"); // 允许指定域名发起的跨域请求
//header("Access-Control-Allow-Origin:http://tieba.baidu.com"); // 允许指定域名发起的跨域请求
echo "saber";

这就ok了。
Read More →

使用Access-Control-Allow-Origin解决Ajax跨域问题