开发者

How to escape & in a POST request in jQuery?

开发者 https://www.devze.com 2023-01-08 08:37 出处:网络
i have an input element with & in value: <input type=\"checkbo开发者_Python百科x\" value=\"Biografie, životopisy, osudy, Domácí rock&amp;pop\" />

i have an input element with & in value:

<input type="checkbo开发者_Python百科x" value="Biografie, životopisy, osudy, Domácí rock&amp;pop" />

When i try sending it through an ajax request:

$.ajax({
    type: "POST",
    url: "/admin/kategorie/add/link.json",
    data: "id="+id+"&value="+value+"&type="+type,
    error: function(){alert('Chyba! Reloadněte prosím stránku.');}
});

the post data that actually gets sent is:

id: 1
pop:
type: e
value: Biografie, životopisy, osudy, Domácí rock

*Note that all the variables in data are defined and value contains $(thatInputElement).attr('value').

How can I escape the &amp; properly so that post field value would contain Biografie, životopisy, osudy, Domácí rock&amp;pop?


You can set your data option as an object and let jQuery do the encoding, like this:

$.ajax({
  type: "POST",
  url: "/admin/kategorie/add/link.json",
  data: { id: id, value: value, type: type },
  error: function(){ alert('Chyba! Reloadněte prosím stránku.'); }
});

You can encode each value using encodeURIComponent(), like this:

encodeURIComponent(value)

But the first option much simpler/shorter in most cases :)


Have you tried this syntax?

 data: {"id":id, "value": value, "type": type }


The javascript function "escape()" should work and on the server the method HttpUtility.UrlDecode should unescape. There may be some exceptions. Additionally if you need to decode on the client, there is an equivalent "unescape()" on the client.


Use the HTML character code for & instead: \u0026


You could create an object and pass that along instead:

vars = new Object();
vars.id = id;
vars.value = value;
vars.type = type;

$.ajax({
  type: "POST",
  url: "/admin/kategorie/add/link.json",
  data: vars,
  error: function(){ alert('Chyba! Reloadněte prosím stránku.'); }
});


you can replace & with {and} at client side, then replace {and} to & at server side

0

精彩评论

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