How to build a URL with an ampersand in one of the request parameter values?

I have an input, comment , which contains "&". How can I use jQuery ajax get method with this value?

For instance:

 index.php?comment=i&you 

where the actual value of the i&you comment field would be incorrect to use as the url.

+4
source share
4 answers

Pass parameters as a map in the second argument (data).

 $.get("index.php", {"comment": "i&you"}); 

jQuery will take care of URL encoding.

See also:


Or, if these values ​​really come from the form, just do

 $.get("index.php", $("#formid").serialize()); 

See also:

+3
source

Use the escape() function:

 var comment = 'i&you'; var url = 'index.php?comment=' + escape(comment); #=> index.php?comment=i%26you 

Edit:

Missed part of jQuery, sorry. In your call to $.ajax() do the following:

 $.ajax('index.php', { 'data': { 'comment': 'i&you', ... } ... }); 

By passing an object (or string) to the data property in the options ( documentation ) argument, you can ensure that your data is properly escaped without having to explicitly do it yourself.

+1
source

I would suggest using the serialize method to add data to your query. Serialize will correctly encode your data for you.

 $.get( 'index.php', $('form').serialize(), function(result) { // do something with result }); 

Or just send one input back:

 $.get( 'index.php', $('input#comment').serialize(), function(result) { // do something with result }); 
+1
source

I'm not too sure what you mean, but to start an AJAX call using jQuery you would do the following:

 $.ajax({ url: "index.php?comment=i&you", context: document.body, success: function(){ // Whatever you need to do goes in this function } }); 
0
source

Source: https://habr.com/ru/post/1345135/


All Articles