首页 > 解决方案 > 无法从 json 响应 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>

和 test.php

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

当我单击请求数据按钮时,它将向“/test.php”发送一个 POST 请求并获得响应

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

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

图片

标签: javascriptphphtmljson

解决方案


You need to parse the JSON into an object before you can extract the specific property values. e.g.

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

推荐阅读