使用Ajax的发送Get请求,Url被截断

在前端开发中,遇到使用Ajax发送Get请求时,由于Url中的roleName参数包含特殊字符'#'导致请求被截断的问题。通过分析发现,encodeURI方法不会对包括'#'在内的特定字符进行编码。解决方法是将encodeURI替换为encodeURIComponent,后者虽然会处理'#',但更适合对Url进行编码,从而解决了请求被截断的难题。

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

  • 请求参数,roleName中包含特殊字符"#"
    请求参数

  • 发送请求的js代码

static request(param){

        let opt = param || {};
        opt.url = param.url || '';
        opt.async = param.async || true;
        opt.data = param.data || null;
        opt.success = param.success || function () {};

        let requestUrl = opt.url;
        requestUrl = this.appendGetParams(requestUrl, opt.data);
        requestUrl = encodeURI(requestUrl);

        $.ajax({
            url: requestUrl,
            contentType: 'application/x-www-form-urlencoded;charset=utf-8',
            type:"get",
            // xhrFields:{
            //     withCredentials:true
            // },
            dataType: opt.dataType || 'json'
        }).done(function (data) {
           ...
           ...
           ...
        });
    }
  • 原因

    encodeURI方法***不会***对下列字符编码 ASCII字母 数字 ~!@#$&*()=:/,;?+'

  • 解决

    将encodeURI替换为encodeURIComponent

    encodeURIComponent方法***不会***对下列字符编码 ASCII字母 数字 ~!*()’,但是会处理"#"

    对url进行encode的时候,根据需要选择不同的编码方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值