dongling4288 2013-11-30 04:20
浏览 30
已采纳

JSON.parse()如何做到这一点?

So... I am trying to use JavaScript to parse an object returned from an PHP file. The relevant code looks like this:

var name = document.getElementBId("name").value;
var XHR = new XMLHttpRequest();
XHR.open("GET', 'lookup.php?name=' + name, true);

XHR.onreadystatechange = function (){
    try{
        alert("Attempting to parse");
        if ((XHR.readyState === 4) && (XHR.status === 200)) {
            alert("Parsing");
            var jsonresponse = JSON.parse(XHR.responseText);
            alert("Is this being skipped?");
        ....

Here's the php being returned:

{
  "name": ABC Elementary, 
  "addr": 3000 County Road 29 Alberta AL 36720-2817, 
  "county": Wilcox, "district": 6;
}

This program is supposed to submit a school's name for a math tournament and use the rest of that info to display the school's address, county, and district once its name has been selected. I picked ABC Elementary as the debugger because it's easy to type.

Unfortunately, the script won't proceed past this point. I'm getting an alert from the alert("Parsing"), but not from alert("Is this being skipped?"). I'm also not getting anything past that point within the XML.onreadystatechange(), although I am still getting alerts from outside the block.

My guess is that it has something to do with how JSON.parse() handles data, or at least it has to do with that line.

Also, I know that other people have asked about this, and I have been looking for these answers, but nobody seems interested in knowing what exactly JSON.parse() is doing to that data. If anyone could enlighten me, I would be very grateful.

  • 写回答

2条回答 默认 最新

  • duanrang9348 2013-11-30 04:42
    关注

    From my understanding, JSON.parse() takes a string value, a stringified object and parses it.

    For JSON.parse() to work for your case, we want the object returned to be:

    {"name": "ABC Elementary", "addr": "3000 County Road 29 Alberta AL 36720-2817", "county": "Wilcox", "district": "6"}
    

    ...BUT we want that wrapped in a string as the input for parse.

    Add this line to your console and press enter and you will see the result of the parse:

    JSON.parse('{"name": "ABC Elementary", "addr": "3000 County Road 29 Alberta AL 36720-2817", "county": "Wilcox", "district": "6"}');
    

    For more information, you can refer to the documentation that might be able to explain it better.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建