为什么我无法获取从PHP获得的对象的属性?

时间:2016-08-15 10:42:29

标签: javascript php ajax

我正在尝试根据用户输入的名称从数据库接收数据,一切正常我看到屏幕上的值并没有错误这是PHP代码:

 <?php
 $dbhost = "localhost";
 $username = "root";
 $password = "";
 mysql_connect($dbhost,$username,$password);
 @mysql_select_db("trynew") or die(mysql_error());
 $user ="mon";  
 $query = "SELECT * FROM trynewtable where name = '$user' ";
 $all_result = array();
 $result = mysql_query($query);
 if($result==FALSE)
 {
  die(mysql_error());
 }
 while($row = mysql_fetch_assoc($result))
 {
 $all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;
mysql_close();
?>

JavaScript代码:

var loadingFunc=function()
{
 var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
 }
else
{
 xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsonData= "";
xhr.onreadystatechange =function()
{
if(xhr.readyState==4)
{
    if(xhr.success =200)
    {
        jsonData = xhr.responseText;
        document.getElementById("dvID").innerHTML = jsonData;
        //var parsejson = JSON.parse(jsonData);
        //document.getElementById("dvIDO").innerHTML = parsejson.age;
        document.getElementById("dvIDO").innerHTML = jsonData[0].age;
    }
    else
    {
        document.getElementIdById("dvID").innerHTML = "it's not success ";
    }
}
else
{
console.log("error is here");
console.log(xhr.readyState);
}
}
var element1 = document.getElementById("dvID") ;
xhr.open("POST","index.php");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
var sendD = document.getElementById("data_found").value;
var data = "data_found=" + sendD;
var element = document.getElementById("btn") ;
if(element)
{
element.addEventListener('click',function(){
console.log("just clicked")
xhr.send(data);
})
}
};

window.onload = loadingFunc();

但是我在html div上看到的输出是:

[{ “ID”: “1”, “名称”: “周一”, “年龄”: “26”, “性别”: “F”}]

未定义

我正在获取整个对象,但每当我尝试获取对象的任何属性时,例如年龄(parsejson.age或jsonData [0] .age)它显示未定义,有人可以帮助我如何获取任何属性对象?

请让我知道我做错了什么?

0 个答案:

没有答案