使用jquery或原生javascript函数编码URL(包括&等字符)

Encoding URL (including characters like &) using jquery or native javascript function?

本文关键字:包括 字符 URL 编码 jquery 原生 javascript 函数 使用      更新时间:2023-09-26

我在表单中有一个隐藏参数,其值为

custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles

我想在发送之前对它进行编码,这样像&可替换为%26 etch

我尝试使用javascript内置的encodeURI("urlToencode"),但不编码字符像&?

试试这行代码,

encodeURIComponent("fisrtName=scott&lastName=Miles");

使用https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent

您需要在URL查询字符串的每个动态部分(名称和值)上调用它。问题是custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles中的URI组件是什么它看起来不像URL因为=?

之前我能做的最有意义的是完整的URL是像 这样的东西
http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
在这种情况下,您应该像 那样构建您的URL
var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);

既然你提到了jQuery,你可以使用$.param,看起来更干净,为你做编码,你可以一次给它多个查询参数

var url  = initialPath + $.param({
    custAdrress: custAddress, 
    otherParam: "paramVal",
    // Both the param name and value need to be encoded and $.param does that for you
    "funny Name & Param": "funny & value ="
});