weixin_33682790 2011-08-06 18:33 采纳率: 0%
浏览 184

在JSON中处理HTML代码

I am writing code that will use AJAX requests to get some HTML code from the server to embed, but I cannot seem to get the JSON format correct. Can anyone tell me what I am doing wrong?

{"response": 
 [
  {"code": "<div id=\”sponsors\” class=\”infoBox\” > <div class=\”title\”>THANK YOU 2011 SPONSORS!</div> <div class=\”section\”> <div class=\”party\”><a href=\”http://www.ChickRussell.com\”>Chick Russell Communications</a></div> <div class=\”cityState\”>Pasadena, California</div> <div class=\”description\”> Chick Russell Communications is a story-driven creative development company, not a design-driven company. It's one of our main distinguishing features. It doesn't matter how great it looks if it doesn't create the desired effect. <a href=\”/vendors/info/17280\”>more...</a> </div> <div class=\”web\”><a href=\”http://www.ChickRussell.com\”>www.ChickRussell.com</a></div> </div>  </div>"
  }
 ]
}

When I try to run JSON.parse() on it, I get a syntax error

Here is the code I am using to read the JSON:

<script language="JavaScript" type="text/javascript">
var newxhr = new XMLHttpRequest()

newxhr.onreadystatechange = getResponse

function getResponse(){
    if(newxhr.readyState == 4) {
        var response = newxhr.responseText;

        console.log(response)

        response = JSON.parse(response)

        newxhr.close;
    }
}

var url = "http://*.*.net/test.json";

newxhr.open("GET", url, true);
newxhr.send(null)
</script>
  • 写回答

3条回答 默认 最新

  • weixin_33726313 2011-08-06 18:36
    关注

    and " are different characters. You need stright quotes, not curly ones. (Tell your browser to zoom in if you can't see the difference … and don't use an editor (e.g. many word processors) that converts to curly quotes automatically, use a proper text editor (I'm fond of ActiveState Komodo)).


    Old answer (before the JSON in the question was revised):

    The first thing you are probably doing wrong, is trying to build JSON by hand. Use a library instead.

    The second thing you are doing wrong is HTML encoding (badly) your quote marks. To escape a " inside a JSON string you represent it as \".

    The third thing (but it could be just that you are giving a poor example) is bothering to use an array for a single object.

    When I try to run JSON.parse() on it, I get a syntax error

    Despite the problems with it, what you have is valid JSON, so that should not happen. You appear to have reduced your test case so far that the problem you are having doesn't appear in it.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器