2012-07-10 67 views
3

我試圖做一個簡單的調用數據從數據庫使用PHP和AJAX。我需要多個結果。因此我使用json方法。但它不工作。使用PHP返回多個值jquery.ajax與json

$.ajax({ 
    type: "POST", 
    data: "qid=162", 
    url: "activity_ajax.php", 
    dataType: json, 
    success: function (data) { 
    alert(data.first); 
    } 
}); 

我activity_ajax.php頁面返回以下

echo "first":"Steven","last":"Spielberg","address":"1234 Unlisted Drive"; 

回答

10

,你可以在一個陣列發送多個數據,然後使用json_encode

$output = array('first'=>'Steven', 
       'last'=>'Spielberg', 
       'address'=>'1234 Unlisted Drive'); 

echo json_encode($output,JSON_FORCE_OBJECT); 

和其他方面,你可以訪問這樣的值

success : function(resp) {(
       alert(resp.first); 
       alert(resp.last); 
       alert(resp.address); 
      }); 
+1

由於diCho返回有效的JSON。它解決了這個問題。我在「問題」中編輯的dataType:「json」參數 – Swadesh 2012-07-10 09:25:31

+0

上缺少那些「」。 – diEcho 2012-07-10 09:28:53

0

你沒有返回有效的JSON ...你的PHP改成這樣:

$temp = array('first' => 'Steven', 'last' => 'Spielberg', 'address' => '1234 Unlisted Drive'); 
echo json_encode($temp); 

,它會返回有效JSON。

json_encode方法從多種來源(關聯數組爲一種)