这是我编写的用于使用AJAX从数据库中获取数据的脚本。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadJSON()
{
var data_file = "http://www.idesigns.com.pk/comingsoon/test/connect.php";
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonObj = xmlhttp.responseText;
document.getElementById("firstname").innerHTML = jsonObj.firstname;
document.getElementById("lastname").innerHTML = jsonObj.lastname;
document.getElementById("ajaxDiv").innerHTML=jsonObj;
}
}
xmlhttp.open("GET", data_file, true);
xmlhttp.send();
}
</script>
<title>JSON</title>
</head>
<body>
<h1>User Details</h1>
<p id="firstname">John</p>
<p id="lastname">Doe</p>
<div id='ajaxDiv'>Your result will display here</div>
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
数据库连接没有错误。
获取和/或回显JSON对象时没有错误
但是当我尝试使用innerHTML显示数据时,我得到以下输出with undefined而不是从对象获取firstname和lastname。
输出:
undefined
undefined
{"id":"1","firstname":"Bruce","lastname":"Lee"}
我无法弄清楚发生了什么。如果有人可以提供帮助吗?请
答案 0 :(得分:4)
您正在尝试使用该字符串,就好像它是一个反序列化的对象。该字符串没有名为firstname
和lastname
的属性。
您需要将字符串解码为对象:
var jsonObj = JSON.parse(xmlhttp.responseText);
然后使用jsonObj.firstname
等代码可以正常工作。 (注意,此时,它不是一个“JSON对象”。它只是一个对象.JSON是一个文本符号;一旦文本被解析,你'不再处理JSON了。)
答案 1 :(得分:0)
您需要先解析JSON。您的responseText
只是一个很棒的大字符串,因此当您尝试访问responseText.firstname
之类的属性时,它会返回undefined
,因为字符串没有firstname
属性。使用此:
var jsonObj = JSON.parse( xmlhttp.responseText );
现在jsonObj
应该是一个对象,而不是一个字符串,其属性对应于服务器发送的数据。
答案 2 :(得分:0)
添加
xmlhttp.responseType = "json"
并相应地更改您的代码。当它是JSON对象时,不要将您的响应视为Text