javascript - 即使在 JSON.parse 之后也会出现“未定义”错误

标签 javascript html

<!DOCTYPE html>
<html>

<head>
  <title>Imagery Gallery</title>
</head>

<body>
  <h2>Location List</h2>

  <!-- image gallery will be displayed in the results <div> -->
  <div id="results"></div>


  <!-- JavaScript codes -->
  <script src="HTTPRequest.js"></script>
  <script>
    //Send request to the server to get the JSON dataset showing the list of locations
    //The URL to request is "http://geopingyin.com/gis/Locations.php"
    //The request function sendHttpRequest(sURL) is defined in the HTTPRequest.js file
    sendHttpRequest("http://geopingyin.com/gis/Locations.php");

    //When the JSON dataset (JSONData, a text string) is successfully returned to the browser,
    //The function handleResponseData(JSONData) will be automatically called.
    //Complete the following function to process the JSON dataset.
    function handleResponseData(JSONData) {
      var obj = JSON.parse(JSONData);
      for (i in obj) {
        i += obj[i] + "<br>";
        document.getElementById("results").innerHTML = i.Locations;

      }

    }

    //place your codes here for the imagery gallery
  </script>
</body>

</html>

每当我运行这段代码时,它都会给我一个“未定义”的答案。经过大量研究后,似乎大多数人都对“未定义”有疑问,因为他们使用的是字符串而不是对象。然而,在我的代码中,我使用 JSON.parse 来创建原始字符串的对象,但它仍然显示为未定义。我希望使用 JSON.parse 来将数组更改为对象,然后循环并显示每个对象,但我似乎不知道如何解决此问题。任何帮助将不胜感激!

这里还有我的 HTTPRequest.js 代码,以防万一

var xmlHttp = createHttpRequestObj(); //Http request object

//Create HTTP request object
function createHttpRequestObj() {
  var xmlHttpObj;
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    try {
      xmlHttpObj = new XMLHttpRequest();
    } catch (e) {
      xmlHttpObj = false;
    }
  } else {
    // code for IE6, IE5
    try {
      xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      xmlHttpObj = false;
    }
  }

  if (!xmlHttpObj)
    alert("Cannot create the Http request object");
  else {
    return xmlHttpObj;
  }
}

//Send HTTP request with the URL
//Function handleServerResponse() will be used to interpret the response 
function sendHttpRequest(sURL) {
  if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
    xmlHttp.open("GET", sURL, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send();
  } else {
    setTimeout(function() {
      sendHttpRequest(sURL);
    }, 1000);
  }
}

//Handel HTTP response
function handleServerResponse() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
      xmlResponse = xmlHttp.responseText;

      //Handle the xmlResponse
      handleResponseData(xmlResponse);
    }
  }
}

谢谢!

最佳答案

当您尝试访问不存在的数据时,会产生

undefined 结果。这可能是由于尝试从实际上是字符串的对象读取对象键而导致的;但从真实对象读取不存在的 key 时同样可能发生(这是代码中出现问题的一部分。)

问题出在您的 handleResponseData 函数中;我在下面评论了它来描述出了什么问题:

function handleResponseData(JSONData) {
  var obj = JSON.parse(JSONData); // so far so good

  /* obj only contains one key, "Locations", so `obj` isn't 
     what you want to be iterating over; instead you want to iterate
     within obj.Locations: */
  for (i in obj) { 
    /* Two problems in this next line: first, it's trying to 
       concatenate objects onto a string (which will result in 
       the string "[object Object]"); second, it's trying to 
       concatenating them onto the iterator, which would
       interfere with the loop: */
    i += obj[i] + "<br>";  

    /* This line should not be inside the loop, and it shouldn't be
       trying to read the Locations key from child objects, because
       that key was on the parent: */
    document.getElementById("results").innerHTML = i.Locations;
  }
}

下面是更正后的版本(我假设 Locations 数组中每个对象的 .Name 键就是您想要的):

var xmlHttp = createHttpRequestObj();
function createHttpRequestObj() {
  // Code for handling obsolete browsers omitted for brevity
  return new XMLHttpRequest();
}

function sendHttpRequest(sURL) {
  if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
    xmlHttp.open("GET", sURL, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send();
  } else {
    setTimeout(function() {
      sendHttpRequest(sURL);
    }, 1000);
  }
}

function handleServerResponse() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
      xmlResponse = xmlHttp.responseText;
      handleResponseData(xmlResponse);
    }
  }
}

sendHttpRequest("https://geopingyin.com/gis/Locations.php");

function handleResponseData(JSONData) {
  var obj = JSON.parse(JSONData);
  var output = "";
  for (i in obj.Locations) {
    output += obj.Locations[i].Name + "<br>";
  }
  document.getElementById("results").innerHTML = output
}
<h2>Location List</h2>
<div id="results"></div>

关于javascript - 即使在 JSON.parse 之后也会出现“未定义”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856853/

相关文章:

javascript - 如何限制codepen RSS feed的结果

javascript - Object.keys(data).forEach 不循环

javascript - 如何停止正在 Chrome 中调试的 JavaScript 程序?

javascript - 尝试使用 Javascript 将 HTML 元素插入另一个 HTML 元素

html - 如何移动添加到购物车按钮旁边的数量输入字段 - wordpress

javascript - 导入空类时出错,错误 TS2307 : Cannot find module 'menu'

javascript - 第二个 yAxes 值未使用 Chart.js 正确绘制图表

html - 有一个空的 anchor 标签可以吗?

javascript - HTML/Javascript anchor 到另一个部分不起作用

javascript - 使用代码从 HTML 表单中获取所有输入字段名称