function createCORSRequest(method, url) {php
var xhr = new XMLHttpRequest();跨域
// 支持cors,检查xhr的withCredentials属性浏览器
if("withCredentials" in xhr) {安全
xhr.open(method, url, true);服务器
}app
// IE8cors
else if(typeof XDomainRequest != "undefined") {post
xhr = new XDomainRequest();url
xhr.open(method, url);spa
} else {
xhr = null;
}
return xhr;
}
function postDataFormat(obj){
if(typeof obj != "object" ) {
alert("输入的参数必须是对象");
return;
}
// 支持有FormData的浏览器(Firefox 4+ , Safari 5+, Chrome和Android 3+版的Webkit)
if(typeof FormData == "function") {
var data = new FormData();
for(var attr in obj) {
data.append(attr,obj[attr]);
}
return data;
}else {
// 不支持FormData的浏览器的处理
var arr = new Array();
var i = 0;
for(var attr in obj) {
arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);
i++;
}
return arr.join("&");
}
}
function getDataFormat(obj) {
if(typeof obj != "object" ) {
alert("输入的参数必须是对象");
return;
}
var arr = new Array();
var i = 0;
for(var attr in obj) {
arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);
i++;
}
return "?" + arr.join("&");
}
cors.onerror = function() {
// 处理错误的代码
};
cors.onload = function() {
// 处理成功的代码
};
var data = {name:"ccb"};
var xhr = createCORSRequest("get", http://www.question.com/php/test.php+ getDataFormat(data));
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.onerror = function() {
alert("跨域请求出错");
};
xhr.send(null);
var data = {name:"ccb"};
var xhr = createCORSRequest("post", "http://www.question.com/php/test.php");
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.onerror = function() {
alert("跨域请求出错");
};
xhr.send(postDataFormat(data));
方法一:Apache配置文件配置
在Apache配置文件(Apache\conf\extra\httpd-vhosts.conf)的<Directory>, <Location>, <Files>或<VirtualHost>的配置里加入如下内容便可:
Header set Access-Control-Allow-Origin *
或
Header set Access-Control-Allow-Origin http://www.test.com(具体站点)推荐
方法二:PHP文件中设置
PHP:只须要使用以下的代码设置便可。
header("Access-Control-Allow-Origin:*");
或
header("Access-Control-Allow-Origin: http://www.test.com ") 推荐具体域名后面不能够加“/”
以上的配置的含义是容许任何域发起的请求均可以获取当前服务器的数据。固然,这样有很大的危险性,恶意站点可能经过XSS攻击咱们的服务器。因此咱们应该尽可能有针对性的对限制安全的来源。使用推荐方式。