【问题标题】:Unable to get value from json response this.responseText?无法从 json 响应 this.responseText 中获取值?
【发布时间】:2021-11-26 18:42:16
【问题描述】:

无法从 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>

和test.php

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

当我点击请求数据按钮时,它会发送一个 POST 请求到“/test.php”并得到响应

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

我想获取 fname 的值,但它显示未定义

image

【问题讨论】:

    标签: javascript php html json


    【解决方案1】:

    您将在xhttp.responseText 或this.responseText 中收到回复。 要获取 fname 和 lname,首先使用 JSON.parse 解析结果,然后使用 Destructuring assignment 从中获取 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;
    

    【讨论】:

      【解决方案2】:

      您需要先将 JSON 解析为一个对象,然后才能提取特定的属性值。例如

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 2021-02-07
        相关资源
        最近更新 更多