javascript 如何在 Angularjs 中编码字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26139407/
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 encode a String in Angularjs?
提问by Pracede
I use Angularjs to send a get http request to my server. The server respond to rest request using Spring MVC. Here a snippet code on my angular url building :
我使用 Angularjs 向我的服务器发送一个 get http 请求。服务器使用 Spring MVC 响应休息请求。这是我的 angular url 构建的片段代码:
var name="myname";
var query= "wo?d";
var url = "/search/"+query+"/"+name;
Here Spring MVC Controller :
这里 Spring MVC 控制器:
@RequestMapping( value = "/search/{query}/{name}" , method = RequestMethod.GET , produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
public List<Data> search() {
// search logic
return data;
}
I have the problem when the query contains question mark character ( ? ). The url is split so that Spring responds : WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/my-server/web/search/wo in DispatcherServlet with name 'mvc'
当查询包含问号字符 ( ? ) 时,我遇到了问题。url 被拆分,以便 Spring 响应:WARN osweb.servlet.PageNotFound - 未找到具有 URI [/my-server/web/search/wo in DispatcherServlet with name 'mvc' 的 HTTP 请求的映射
This is right because the question marks ? introduce the begining of request parameters.
I've tried to use the js function encodeURI(query)
but the question mark character is not encoded. How to encode a question mark in url ?
Thanks
这是对的,因为问号?介绍请求参数的开头。我尝试使用 js 函数,encodeURI(query)
但问号字符未编码。如何在 url 中编码问号?谢谢
回答by dfsq
Javascript has special function for this purpose encodeURIComponent
Javascript 为此具有特殊功能encodeURIComponent
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
encodeURIComponent 转义除以下字符之外的所有字符:字母、十进制数字、 - _ 。!~ * ' ( )
while encodeURI
also does not encode ; , / ? : @ & = + $ #
characters.
whileencodeURI
也不编码; , / ? : @ & = + $ #
字符。