javascript 如何在 url 中将特殊字符作为查询字符串传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17131869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass special characters as query string in url
提问by Ganesh
I am trying to pass special characters as querystring in url as part of GET request. I am constructiong that string in javascript function.
我正在尝试将特殊字符作为 url 中的查询字符串作为 GET 请求的一部分传递。我正在 javascript 函数中构造该字符串。
var queryString = "list=ABC-48+12&level=first";
Then I append the string to url as part of request which goes to struts action class. In the action class I get the "list" value as "ABC-48 12"
, the "+"
character is not passed.
How to pass special characters in the string as part of url and get back in the java class?
然后我将字符串附加到 url 作为请求的一部分,该请求将发送到 struts 操作类。在操作类中,我将“列表”值设为"ABC-48 12"
,"+"
字符未通过。如何将字符串中的特殊字符作为 url 的一部分传递并返回 java 类?
Please let me know.
请告诉我。
Thanks.
谢谢。
采纳答案by Ryder
You need to use a regular expression with the global option set as the first parameter instead of a string: (in regular expressions "+" is a special character, so we have to escape it with a backslash.)
您需要使用将全局选项设置为第一个参数而不是字符串的正则表达式:(在正则表达式中,“+”是一个特殊字符,因此我们必须使用反斜杠对其进行转义。)
safeQueryString = safeQueryString.replace(/+/g, '%2B');
safeQueryString = safeQueryString.replace(/+/g, '%2B');
回答by Darin Dimitrov
You should url encode it using the encodeURIComponent
function:
您应该使用以下encodeURIComponent
函数对其进行 url 编码:
var queryString =
"list=" + encodeURIComponent("ABC-48+12") +
"&level=" + encodeURIComponent("first");
This function will take care of properly encoding your query string parameter values:
此函数将负责正确编码您的查询字符串参数值:
list=ABC-48%2B12&level=first