javascript - 无法从 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 的值,但它显示未定义
解决方案
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;
}
推荐阅读
- javascript - 有没有办法制作电子表格文件的多个副本并在 Google Apps 脚本中为每个文件选择名称
- html - 给我元素“head”的 HTML Validator 缺少子元素“title”的必需实例
- javascript - 根据指定的长度用 null 填充剩余的数组索引
- python - Discord bot 在我运行命令时显示错误,但有时仍会运行命令
- java - org.postgresql.util.PSQLException:int 类型的值错误:(简单的 JDBC 插入)
- r - 过滤数据列有某字
- java - 如何在 Android API 22 上创建 AES 密钥并通过私钥对其进行加密?
- python - CXFreeze:ModuleNotFoundError:没有名为“skimage.feature._orb_descriptor_positions”的模块
- reactjs - 错误:我的模态组件超出了最大更新深度
- amazon-web-services - 为 Neptune 构建 http REST API 请求的 AWS 授权标头