H5开发中使用ajax调用数据接口, 如果接口文件不在同域名下会提示跨域错误(No ‘Access-Control-Allow-Origin’ header is present on the requested resource.)。
解决方法
通过设置php接口文件的 Access-Control-Allow-Origin 头信息来实现跨域访问。
// 1、允许单个域名访问
header("Content-type:application/json; charset=utf-8");
header("Access-Control-Allow-Origin:http://bm.tihu.com");
// 设置是否允许发送 cookies
header("Access-Control-Allow-Credentials:true");
header('Access-Control-Expose-Headers: *'); //服务器 headers 白名单,可以让客户端进行访问
header('Access-Control-Allow-Headers: *');
// 2、允许多个域名访问
header("Content-type:application/json; charset=utf-8");
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://client1.tihu.com',
'http://client2.tihu.com'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
header("Access-Control-Allow-Credentials:true");
// 3、允许所有域名访问
header('Access-Control-Allow-Origin:*');