当字符串包含HTML标记时,JSON无法解析

时间:2012-08-12 15:27:38

标签: javascript jquery

为什么这个ajax在将jtml标签添加到json时失败,如果<br />不在那里则可行。我能想到的唯一工作就是对文本进行编码。

你知道为什么或/并有任何其他建议。

由于

 $.ajax({
            type: "POST",
            url: "/url",
            //data: { "myText" : '[{ "a": "test1", "b": "test2"}]' },//works
            data: { "myText": '[{ "a": "<br />dfgdfgdfgdfgdgd", "b": "test2"}]' },//causes error
            dataType: 'json',
            success: function (data) {
                        alert("pass");
            },
            error: function () {
                        alert("error");

            }
        });

1 个答案:

答案 0 :(得分:3)

尝试使用JSON.stringify方法:

data: { "myText": JSON.stringify([{ "a": "<br />dfgdfgdfgdfgdgd", "b": "test2"}]) }

或者如果您不想发送myText作为JSON字符串删除单引号:

data: { "myText": [{ "a": "<br />dfgdfgdfgdfgdgd", "b": "test2"}] }

当然,如果在服务器端使用某些技术(例如ASP.NET)禁止在请求中使用< >等字符,则必须修复服务器端脚本,以便它接受这些字符。

相关问题