2016-03-07 50 views
-1

這是一個非常簡單的問題,但我現在正在爲這兩個小時苦苦掙扎。php json_encode不會給出純粹的對象

我有一個PHP文件:

$array = array(
     "id"=> 1, "firstName"=> "James", "lastName"=> "King", "managerId"=> 0, "managerName"=> "", "title"=> "President and CEO", "department"=> "Corporate", "cellPhone"=> "617-000-0001", "officePhone"=> "781-000-0001", "email"=> "[email protected]", "city"=> "Boston, MA", "pic"=> "James_King.jpg", "twitterId"=> "@fakejking", "blog"=> "http://coenraets.org" 
    ); 
echo json_encode($array); 

現在我想這給像下面這樣的對象:

Object 
blog: "http://coenraets.org" 
cellPhone: "617-000-0001" 
city: "Boston, MA" 
department: "Corporate" 
email: "[email protected]" 
firstName: "James" 
id: 1 
lastName: "King" 
managerId: 0 
managerName: "" 
officePhone: "781-000-0001" 
pic: "James_King.jpg" 
title: "President and CEO" 
twitterId: "@fakejking" 

現在,我發現了以下回應:

abort: (a) 

always:() 

complete:() 

done:() 

error:() 

.... 

readyState: 4 

responseText: "{"id":1,"firstName":"James","lastName":"King","managerId":0,"managerName":"","title":"President and CEO","department":"Corporate","cellPhone":"617-000-0001","officePhone":"781-000-0001","email":"[email protected]","city":"Boston, MA","pic":"James_King.jpg","twitterId":"@fakejking","blog":"http:\/\/coenraets.org"}" 

setRequestHeader: (a,b) 

state:() 

... 

__proto__: Object 

我真的不知道去哪裏看,很可能做錯了什麼,但我真的不知道。

UPDATE

JS

var result = $.ajax({ 
      url: "http://localhost/cordova/employees/index.php?name="+ searchKey, 
      context: document.body 
     }); 
    console.log(JSON.parse(result.responseText)); 

線的console.log(JSON.parse(result.responseText))給了我以下錯誤:

Uncaught SyntaxError: Unexpected token o 
+0

響應文本是你的JSON對象。其餘的東西是圍繞請求發出的上下文。 –

+0

你是否設置了標題類型? – Kisaragi

+0

你的JavaScript代碼是什麼樣的? – MonkeyZeus

回答

3

那是因爲你看着XMLHttpRequest對象。您需要解析出獲取對象的響應。

var obj = JSON.parse(xhr.responseText); 

其中xhr是對象的名稱,你正在做一個console.log

+0

如果我添加了這個,我收到一個錯誤:Uncaught SyntaxError:意外的代幣u有時候其他時間o – user3398922

+1

@ user3398922請確保您傳遞的是正確的數據。你可能會傳遞'undefined'而不是'responseText'中的正確字符串。如果你展示瞭如何在你的問題中輸出結果,這將會容易得多。 –

0

$.ajax()發出一個異步HTTP請求,所以你不能只是得到正確的響應方式。你必須等待迴應來找你。當您的響應已準備就緒時,done()結構可用於觸發回調。

var getEmployee = $.ajax({ 
    url: "http://localhost/cordova/employees/index.php?name="+ searchKey, 
    context: document.body, 
    dataType: 'json' 
}); 
// the callback will get fired when the response is received 
getEmployee.done(function (result) { 
    console.log(result.blog); 
}); 
// this will get fired immediately before the response is even received 
console.log(getEmployee.responseText); 
0

這是一個簡單的功能。 在PHP 瞭解stdClass的和修改你的PHP代碼:

$array = new stdClass(); 
$array->id = 1; 
$array->firstName = "James"; 
//..... other fields 
echo json_encode($array);