You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XMLHttpRequest中发送含&符号的POST参数(不使用encodeURIComponent)

不使用encodeURIComponent处理POST参数中的&符号问题

当用XMLHttpRequest发送POST请求时,如果参数值里包含&,直接用application/x-www-form-urlencoded格式拼接字符串会让后端把&当成参数分隔符,导致解析出错。不用encodeURIComponent的话,有下面几种可行方案:

方案1:用FormData自动处理参数

FormData会自动处理所有特殊字符(包括&),无需手动拼接编码,是最省心的替代方案。修改代码如下:

// 用FormData构建参数集合
const formData = new FormData();
formData.append('action', foo);
formData.append('token', bla);

xhrRequest = new XMLHttpRequest();
xhrRequest.onreadystatechange = function() {
    if (xhrRequest.readyState == 4) {
        // 处理响应逻辑
    }
}
xhrRequest.onerror = function(e) { 
    // 处理错误逻辑
};
xhrRequest.open('POST', url);
// 无需手动设置Content-Type,浏览器会自动添加正确的请求头
xhrRequest.send(formData);

方案2:改用JSON格式提交

将参数转为JSON字符串发送,后端直接解析JSON内容,这样&就不会被当成参数分隔符。需要修改请求的Content-Type为application/json:

// 把参数转为JSON字符串
const params = JSON.stringify({
    action: foo,
    token: bla
});

xhrRequest = new XMLHttpRequest();
xhrRequest.onreadystatechange = function() {
    if (xhrRequest.readyState == 4) {
        // 处理响应逻辑
    }
}
xhrRequest.onerror = function(e) { 
    // 处理错误逻辑
};
xhrRequest.open('POST', url);
xhrRequest.setRequestHeader("Content-Type", 'application/json');
xhrRequest.send(params);

注意:后端需要支持解析JSON格式的请求体,比如Node.js中使用express.json()中间件,PHP中用json_decode(file_get_contents('php://input'))来获取解析内容。

方案3:手动替换参数值中的&(不推荐)

如果一定要坚持用application/x-www-form-urlencoded格式,又不想用encodeURIComponent,可以手动把参数值里的&替换成URL编码后的%26,但要注意只替换参数值内的&,不要误改分隔用的&:

// 仅替换参数值里的&符号
const safeFoo = foo.replace(/&/g, '%26');
const safeBla = bla.replace(/&/g, '%26');
var params = `action=${safeFoo}&token=${safeBla}`;

xhrRequest = new XMLHttpRequest();
xhrRequest.onreadystatechange = function() {
    if (xhrRequest.readyState == 4) {
        // 处理响应逻辑
    }
}
xhrRequest.onerror = function(e) { 
    // 处理错误逻辑
};
xhrRequest.open('POST', url);
xhrRequest.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
xhrRequest.send(params);

这种方法仅处理了&,但其他特殊字符(比如=、+、空格)仍会引发解析问题,除非特殊场景,不建议使用。

内容的提问来源于stack exchange,提问作者Toniq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 01:47:06