JS跨域问题有两个解决方案:
一、前端程序解决;
二、后端程序解决(推荐);
一、前端程序解决
缺点:只支持GET请求(假如前端强制使用POST,JSONP自动将参数转为GET)
前端如下:
$.ajax({
url: "...",
data: {
id: 9
},
dataType: 'json',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'data', // 主要用来识别,好像没其他用途,删掉的话jquery就随机生成一个名称,删掉也可以
success: function (res) {
console.log(res);
},
error: function (e) {
console.log(e.status, e.responseText);
}
});
后端如下(YII2为例):
public function actionTest($id = 0, $callback = '')
{
$res = [
'statusCode' => 200,
'message' => 'success',
'data' => [
'id' => $id,
]
];
$response = Yii::$app->response;
$response->format = $callback ? \yii\web\Response::FORMAT_JSONP : \yii\web\Response::FORMAT_JSON;
$response->data = $callback ? ['callback' => $callback, 'data' => $res] : $res;
}
二、后端程序解决
缺点:(好像没啥缺点)
前端如下:
$.ajax({
url: "...",
data: {
id: 9
},
dataType: 'json',
type: 'POST',
success: function (res) {
console.log(res);
},
error: function (e) {
console.log(e.status, e.responseText);
}
});
后端如下(YII2为例):
use yii\filters\Cors;
public function behaviors()
{
return [
'corsFilter'=>[
'class' => Cors::className(),
'cors'=>[
// restrict access to
// 'Origin' => ['*'],
'Origin' => ['http://www.domain.com'],
'Access-Control-Request-Method' => ['POST', 'GET'],
// Allow only headers 'X-Wsse'
// 'Access-Control-Request-Headers' => ['X-Wsse'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'Access-Control-Allow-Credentials' => false,
// Allow OPTIONS caching
// 'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
// 'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
]
]
];
}
public function actionAdvHomeBannerJsonCor()
{
$post_data = Yii::$app->request->post();
$res = [
'statusCode' => 200,
'message' => 'success',
'data' => [
'id' => $post_data['id'],
]
];
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = $res;
}