php接口,解决跨域的构造函数
/*
* 解决跨域,并统一接收参数--析构方法
*/
protected function _initialize()
{
//比其他跨域多了Access-Control-Allow-Credentials,允许携带Cookie
header('Access-Control-Allow-Credentials: true');
header('content-type:text/html;charset=utf-8');
//而且起源不能是通配符'*',必须为具体网址
header('Access-Control-Allow-Origin: http://localhost:8080');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
}
也可以在index.php头加
header('Access-Control-Allow-Credentials: true');
header('content-type:application:json;charset=utf8');
//header('Access-Control-Allow-Origin: https://test.easyketang.com');
header('Access-Control-Allow-Origin: http://localhost:8080');
header('Access-Control-Allow-Methods:PUT,POST,GET,OPTIONS,DELETE');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
jquery的$.ajax写方法示例
$.ajax({
type : "POST",
url : this.apiUrl+"login",
contentType: "application/json",
xhrFields: {
withCredentials: true
},
data: JSON.stringify(this.user),
success : function(response) {
console.log(JSON.parse(response));
},
error : function(response){
console.log(JSON.parse(response));
}
});