'未定义'即使在JSON.parse之后也会出错

时间:2018-02-18 21:36:04

标签: 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>

这段代码给了我一个未定义的&#39;每当我运行它时都会回答。经过大量研究后,似乎大多数人都会遇到“未定义”的问题。因为他们使用字符串而不是对象。但是在我的代码中,我使用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);
    }
  }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

当您尝试访问不存在的数据时,会出现

undefined。这个可以来自尝试从实际上是一个字符串读取一个对象密钥;但是当从真实对象中读取不存在的键时(这是代码中出错的一部分),同样会发生这种情况。)

问题在您的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;
  }
}

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

&#13;
&#13;
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
}
&#13;
<h2>Location List</h2>
<div id="results"></div>
&#13;
&#13;
&#13;