1 回答

TA貢獻(xiàn)1820條經(jīng)驗 獲得超2個贊
問題是您正在嘗試訪問一個對象,但 API 的輸出實(shí)際上是一個數(shù)組。jsonObj[0]您可以通過執(zhí)行以下操作來獲取第一個對象:
<html>
<body>
? ? ? <table class = "src">
? ? ? ? ?<tr><th>Name</th><th>id</th></tr>
? ? ? ? ?<tr><td><div id = "Name"></div></td>
? ? ? ? ?<td><div id = "Id"></div></td></tr>
? ? ? </table>
? ?</body>
</html>
<script type="text/javascript">
? ?var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
? ?xmlhttp.onreadystatechange = function(e) {
? ? ? ? ? ? ? ?if (this.readyState == 4 && this.status == 200)? {
? ? ? ? ? ? ? ? ? // Javascript function JSON.parse to parse JSON data
? ? ? ? ? ? ? ? ? var jsonObj = JSON.parse(this.responseText);
? ? ? ? ? ? ? ? ? // jsonObj variable now contains the data structure and can
? ? ? ? ? ? ? ? ? // be accessed as jsonObj.name and jsonObj.country.
? ? ? ? ? ? ? ? ? document.getElementById("Name").textContent = jsonObj[0].name;
? ? ? ? ? ? ? ? ? document.getElementById("Id").textContent = jsonObj[0].id;
? ? ? ? ? ? ? ?}
? ? ? ? ? ? }
? ? ? ? ? ? ?xmlhttp.open("GET", url, true);
? ? ? ? ? ? xmlhttp.send();
</script>
請參閱代碼運(yùn)行的代碼和框。
最好使用textContent
而不是innerHTML
避免呈現(xiàn)不需要的 HTML(永遠(yuǎn)不要相信用戶輸入?。?。
- 1 回答
- 0 關(guān)注
- 144 瀏覽
添加回答
舉報