0

我正在使用生成一个 json 字符串JSON.stringify,我的 json 字符串会像

jsonstring=[{"step1":[{"nm":"John & joe"},{"title":"Hello & hai"}]},{"step2":[{"desc":"1234"},{"usr":"abc@xyz.com"}]}]` 

我正在转义&\&通过 ajax 将此 json 字符串发送到服务器。

$.ajax({
url:"test-usr-data.php",
type:"post",
data:"usrdata="+jsonstring,
success: function(response){
console.log("data is "+response); 
},
complete:function (jqXHR, textStatus){ 
console.log("ajax Request completed"+textStatus);
    }
});

问题在于&json 字符串中的 char,即使我转义&\&数据未发布到服务器但 ajax 请求状态为成功。

我尝试&从 json 字符串中删除它工作正常并且数据正确发布到服务器。

任何人都可以帮助我以正确的方式&在 json 字符串中转义。

4

2 回答 2

3

Who told you that escaping in URL's works by prepending a backslash?

jQuery will take care of it, just do

data: {usrdata: jsonstring},

FYI: You could use encodeURIComponent as well

data: "usrdata=" + encodeURIComponent(jsonstring),
于 2012-10-07T15:41:07.680 回答
0

The way to URI encode a & is as %26, given that 0x26 (38) is the ASCII code for that character.

But don't, use the data: { key: value, ... } way of passing parameters to $.ajax instead, and have jQuery do it all for you.

于 2012-10-07T15:43:08.077 回答