簡體   English   中英

無法從 json 響應 this.responseText 中獲取值?

[英]Unable to get value from json response this.responseText?

無法從 json 響應中獲取值這是我的 html。

索引 html

<!DOCTYPE html>
<html>
<head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Request data</button>
<br>
<br>

<p id="demo"></p>
<p id="demo1"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML ="JSON  =  "+this.responseText;
      document.getElementById("demo1").innerHTML = "first name =  "+this.responseText.fname;
    }
  };
  xhttp.open("POST", "/test.php", true);
  xhttp.setRequestHeader("Content-type", "application/json");
  xhttp.send();
}
</script>

</body>
</html>

和測試.php

<?php
echo '{"fname":"sumith","lname":"emmadi"}'
?>

當我單擊請求數據按鈕時,它會向“/test.php”發送一個 POST 請求並得到響應

{"fname":"sumith","lname":"emmadi"}

我想獲取 fname 的值,但它顯示未定義

圖片

您需要先將 JSON 解析為 object,然后才能提取特定的屬性值。 例如

if (this.readyState == 4 && this.status == 200) {
  var data = JSON.parse(responseText);
  document.getElementById("demo1").innerHTML = "first name =  "+ data.fname;
}

您將在xhttp.responseTextthis.responseText中得到響應。 要獲取fnamelname ,首先使用JSON.parse解析結果並使用解構賦值從中獲取 fname 和 lname

const { fname, lname } = JSON.parse(xhttp.responseText);

// To show in DOM
document.getElementById("demo").innerHTML ="JSON  : <pre> " + xhttp.responseText + "</pre>";

document.getElementById("demo1").innerHTML = "first name =  " + fname;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM