Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a String in Angularjs?

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 :

var name="myname";
var query= "wo?d";
var url = "/search/"+query+"/"+name;

Here Spring MVC Controller :

@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'

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

like image 857
Pracede Avatar asked Oct 01 '14 10:10

Pracede


2 Answers

Javascript has special function for this purpose encodeURIComponent

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

while encodeURI also does not encode ; , / ? : @ & = + $ # characters.

like image 158
dfsq Avatar answered Nov 07 '22 00:11

dfsq


Use encodeURIComponent for that.

check this fiddle.

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

For angular specific look this SO answer.

still some problem then post me.

like image 4
user3145373 ツ Avatar answered Nov 07 '22 01:11

user3145373 ツ