我有2个表从数据库中检索,有2个不同的查询,需要在json中编码并发送到ajax。问题是我无法将2个json传递给ajax。 我试过echo echo json_encode(array($ data1,$ data2));但它没有用。
//我的PHP代码
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1['value1'] = $row['value1'];
$data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2['value2'] = $row['value2'];
$data2['value3'] = $row['value3'];
}
echo json_encode(array($data1,$data2));
//我的AJAX代码
$(document).ready(function(){
$('#Form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"json",
success:function(data){
//main
alert(data.value1);
},
error:function(err){
alert(err);
}
});
});
});
请帮助解决这个问题。谢谢提前
答案 0 :(得分:2)
在PHP中:
echo json_encode(array($data1, $data2));
在AJAX中:
var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
console.log(this.value2 + ',' + this.value3);
});
修改强> 经过整整一年,我只是注意到最初的PHP代码是错误的,因为sql结果的循环每次都会覆盖数组的值。所以,正确的是:
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}
echo json_encode(array($data1,$data2));
答案 1 :(得分:0)
您的代码很好,您只需处理成功函数中的两个数组:
success: function(data){
var object1 = data[0];
var object2 = data[1];
// Do whatever you like to do with them
}