第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 javascript 面對 json 中的未定義錯誤

使用 javascript 面對 json 中的未定義錯誤

千萬里不及你 2024-01-11 14:26:34
我正在使用 javascript ajax 從 JSON API 服務(wù)器獲取數(shù)據(jù),并希望在 HTML 表中顯示這些數(shù)據(jù)。但我在 HTML 數(shù)據(jù)中收到未定義的錯誤。那是Name         idundefined undefined有我的代碼<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").innerHTML = jsonObj.name;                  document.getElementById("Id").innerHTML = jsonObj.id;               }            }             xmlhttp.open("GET", url, true);            xmlhttp.send();</script>我應(yīng)該怎么做才能解決這個問題?提前致謝。
查看完整描述

1 回答

?
DIEA

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)不要相信用戶輸入?。?。


查看完整回答
反對 回復(fù) 2024-01-11
  • 1 回答
  • 0 關(guān)注
  • 144 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號