php ajax跨域问题解决方案

本文经过设置Access-Control-Allow-Origin来实现跨域。php

例如:客户端的域名是client.runoob.com,而请求的域名是server.runoob.com。html

若是直接使用ajax访问,会有如下错误:ajax

XMLHttpRequest cannot load http://server.runoob.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.runoob.com' is therefore not allowed access.跨域

一、容许单个域名访问

指定某域名(http://client.runoob.com)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加以下代码:spa

header('Access-Control-Allow-Origin:http://client.runoob.com');

二、容许多个域名访问

指定多个域名(http://client1.runoob.com、http://client2.runoob.com等)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加以下代码:
$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); }

三、容许全部域名访问

容许全部域名访问则只需在http://server.runoob.com/server.php文件头部添加以下代码:server

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


转载自:http://www.javashuo.com/article/p-uspoykyo-ko.html
相关文章
相关标签/搜索