JS跨域问题解决方案

本文介绍了解决JS跨域问题的两种方法:一是前端通过JSONP实现GET请求;二是后端配置CORS支持任意请求方式。文章提供了具体代码示例,包括前端jQuery的JSONP调用及后端YII2的CORS设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值