How to escape & in a POST request in jQuery?

十年热恋 提交于 2019-12-17 16:46:13

问题


i have an input element with & in value:

<input type="checkbox" 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?


回答1:


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 :)




回答2:


Have you tried this syntax?

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



回答3:


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.




回答4:


Use the HTML character code for & instead: \u0026




回答5:


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.'); }
});



回答6:


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



来源:https://stackoverflow.com/questions/3319123/how-to-escape-in-a-post-request-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!