我的AJAX:從ajax調用中檢索json_encoded的PHP對象值?
$.ajax(
{
type:'POST',
url: 'ajax.php', //the script to call to get data
data: {request: 'getUser',id:id},
dataType: 'json', //data format
complete: function(data) //on receive of reply
{
console.log(data);
}
});
我的PHP文件,處理AJAX請求(ajax.php):
elseif ($_POST['request'] == 'getUser')
{
$DAO = new UserDAO;
$q = $DAO->ajaxGetUser($_POST['id']);
echo json_encode($q);
}
ajaxGetUser
功能:
public function ajaxGetUser($id)
{
$q = $this->db->prepare('SELECT * FROM user WHERE userId=:id');
$q->bindValue(':id', $id, PDO::PARAM_INT);
$q->execute();
$r = $q->fetch(PDO::FETCH_OBJ);
unset($r->userPassword);
return $r;
}
console.log(data)
是顯示我的對象螢火蟲上的「ResponseJSON」,但當我嘗試像console.log(data.userName)
,console.log(data[0].userName)
這樣的東西時,它們是未定義的,因爲我是n在Ajax非常好,我一直在尋找很多線程,但找不到可以幫助我的線程。
我猜json已經被解析了,因爲dataType
被設置爲「json」,我如何訪問User對象的所有屬性?感謝您的幫助
readyState 4
responseJSON
Object { userId="6", userName="321", more...}
responseText
"{"userId":"6","userName...":null,"userStatus":"0"}"
status 200
statusText "OK"
abort function()
always function()
complete function()
done function()
error function()
fail function()
getAllResponseHeaders function()
getResponseHeader function()
overrideMimeType function()
pipe function()
progress function()
promise function()
setRequestHeader function()
state function()
statusCode function()
success function()
then function()
你能後的'的console.log(數據)的輸出'? – tymeJV