我需要在HTML(JSON响应)中转义什么

时间:2009-06-14 22:56:28

标签: javascript asp.net-mvc json

我的JSON响应如下:

{rc: "200", test: "", user: "<div class='sub1'>
                <div class='avatar'>                    
                    <a href='/blah'>blah</a><br />
                    <strong>0</strong>
                </div>
                <div class='sl'>
                    <p>
                        you droppped the ball this time
                    </p>
                </div>
                <div class='clear'>
                </div>                        
            </div>"}

更新

我更新了我的代码以在键值上加上引号,但仍不起作用:

{"rc": "200", "m" : "", "o": "<div class='s1'>
            <div class='avatar'>                    
                <a href='\/asdf'>asdf<\/a><br \/>
                <strong>0<\/strong>
            <\/div>
            <div class='sl'>
                <p>
                    444444444
                <\/p>
            <\/div>
            <div class='clear'>
            <\/div>                        
        <\/div>"}

4 个答案:

答案 0 :(得分:3)

我使用jsonlint来验证您的最新示例,并且换行符是它标记的内容。当它们被删除时,它会被验证。

{
    "rc": "200",
    "m" : "",
    "o": "<div class='s1'><div class='avatar'><a href='\/asdf'>asdf<\/a><br \/><strong>0<\/strong>      <\/div>    <div class='sl'><p>444444444<\/p><\/div><div class='clear'><\/div><\/div>"
}

答案 1 :(得分:1)

在你的例子中,你不必逃避任何事情。但是,如果HTML带有双引号,显然你必须逃避它们。

答案 2 :(得分:1)

您的HTML值是可以的,但JSON对象的键必须用引号括起来。

来自JSON RFC

  

2.2。对象

     

表示对象结构   作为一对花括号
  包含零个或多个名称/值   对(或成员)。名字是一个   字符串。

  

2.5。字符串

     

字符串的表示是   类似于C中使用的惯例   编程语言家族。一个   字符串以
开头和结尾   引号。

此外,如果您在HTML页面的脚本标记内输出此JSON对象,则必须按照this appendix in the HTML 4 specification转义HTML结束标记的“&lt; /”序列。

答案 3 :(得分:-1)

您不需要在javascript字符串中转义HTML。你究竟想做什么/有什么问题?看一下escape()函数 - 它可能会有所帮助。

相关问题