开发者

How do construct a url that has an ampersand in one of the query parameter values?

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

For example:

index.php?comment=i&you

where开发者_JAVA技巧 the actual value of the comment field is i&you would be wrong to use as the url.


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

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

jQuery will take care about URL encoding.

See also:

  • jQuery.get() API doc

Or if those values actually come from a form, just do

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

See also:

  • jQuery.serialize() API doc


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

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

Or if just sending one input back:

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


Use the escape() function:

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

Edit:

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

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

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


I'm not too sure what you mean, but to run an AJAX call with 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜