PHP解决ajax跨域的问题

跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

同源策略:同源策略/SOP(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS、CSFR等攻击。所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个ip地址,也非同源。

常见跨域方法

1、允许单个域名访问

指定某域名(http://client.runoob.com)跨域访问,则只需添加如下代码:

public function test(){
    //单个跨域
    header('Access-Control-Allow-Origin:http://www.runoob.com');
    return json(["code"=>1,"name"=>"lhs"]);
}

2、允许多个域名访问

指定多个域名(http://client1.runoob.com、http://client2.runoob.com等)跨域访问,则只需添加如下代码:

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';  
  
$allow_origin = array(  
    'http://client1.runoob.com',  
    'http://client2.runoob.com'  
);  
  
if(in_array($origin, $allow_origin)){  
    header('Access-Control-Allow-Origin:'.$origin);       
} 

3、允许所有域名访问

允许所有域名访问则添加如下代码:

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

4、使用JSONP跨域

使用JSONP跨域则添加如下代码:

public function test(){
    return jsonp(["code"=>1,"name"=>"lhs"]);
}

使用ajax获取数据如下代码:

$.ajax({
    type:"get",
    url:"http://tp51hr.com/api/index/test",
    dataType : "JSONP",//必须
    success:function(res){
        console.log(res)
    }
});
原文地址:https://www.cnblogs.com/bushui/p/12687185.html