在php文件的最前面设置header函数的内容,即在<!doctype html>的前面设置header()函数
1、header("Content-Type: text/html;charset=utf-8");
这句话的意思是,设置页面的内容为html;’编码为utf8(设置编码为utf8的原因是,防止在php文件里面有汉字输出的时候,出现编 码乱码的现象出现)
2、header("Access-Control-Allow-Origin: http://www.funwall.cn"); 设置跨域请求的源
Access-Control-Allow-Origin这个标志用来设置跨域请求
Access-Control-Allow-Origin:*;这里表示允许任何域的请求
Access-Control-Allow-Origin:http://www.funwall.cn;这里用的是具体的url,即表示允许来自该域的访问
同时在ajax请求里面设置属性crossDomain: true,即允许跨域
3、 header('Access-Control-Allow-Credentials: true');发送Cookie的设置认证属性
属性withCredentials(证书):默认情况下,CORS不会发送Cookie和HTTP的认证信息,如果要把Cookie发送到服务器,一方 面要服务器同意,设置属性withCredential,即header('Access-Control-Allow-Credentials: true')。
同时必须在Ajax请求中打开属性withCredentials,即xhrFields: { withCredentials: true }
注意:如果发送Cookie,Access-Control-Allow-Origin就不能设置为*,必须指定明确的、与请求网页一致的域名
4、header('Access-Control-Allow-Headers:x-requested-with,content-type'); 响应头设置
5、 header("location:http://www.funwall.cn/banch/front/index.html);重定向URL,即页面跳转到
http://www.funwall.cn/banch/front/index.html
前端的ajax请求的代码封装成函数:
function request(url,data,success_callback,error_callback) {
console.log("url:"+url);
var xhr = $.ajax({
//提交数据的类型 POST GET
type: "POST",//提交的网址
url: url,//提交的数据
data: data,// 设置超时的时间20s
timeout:20000,//返回数据的格式
datatype: "json",//"xml","html","script","json","jsonp","text".
xhrFields: {
withCredentials: true //设置发送Cookie
},crossDomain: true,//设置跨域请求
//在请求之前调用的函数
beforeSend: function () {
},//成功返回之后调用的函数
success: function (response) {
handleResponse(response,error_callback);
},//调用执行后调用的函数
complete: function (XMLHttpRequest,textStatus) {
if(textStatus == 'timeout'){
if (error_callback != null && error_callback != "") {
error_callback();
};
}
$('#loding').css("display","none");
},//调用出错执行的函数
error: function () {
//请求出错处理
console.log("error");
}
});
}
原文地址:https://blog.csdn.net/tangxiujiang
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。