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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:33:59  来源:igfitidea点击:

How to encode a String in Angularjs?

javajavascriptangularjsspringspring-mvc

提问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 encodeURIalso does not encode ; , / ? : @ & = + $ #characters.

whileencodeURI也不编码; , / ? : @ & = + $ #字符。

回答by user3145373 ツ

Use encodeURIComponentfor that.

encodeURIComponent为此使用。

check thisfiddle.

检查这个小提琴。

var a = "wo?d";
alert(encodeURIComponent(a));

For angular specific look this SOanswer.

对于角度特定的外观,这个 SO答案。

still some problem then post me.

还有一些问题,然后发布我。