2012-07-10 65 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方法从多种来源(关联数组为一种)