![](/img/trans.png)
[英]PHP-JQuery-Ajax: How to Populate table with all results from mysql query result (json encoded array)
[英]How to pull 2 results from PHP Mysql with AJAX and json
大家好,我需要以下幫助代碼,
我正在嘗試使用json將2種不同的結果從mysql php拉到ajax。
這是我目前所擁有的。
我可以拉1表的信息,但不知道如何拉2個不同的結果。 請幫我。
PHP文件
$id = $_POST["order"];
$order = mysql_query("SELECT * FROM `orders` WHERE `order_id` = {$id} ORDER BY id DESC");
$test_quote = mysql_query("
SELECT paid
FROM `outstanding`
WHERE order_id = {$id}
");
$array = array();
//pulling outstanding if product paid or not
if(mysql_num_rows($test_quote) > 0 ){
$array[] = mysql_fetch_array($test_quote);
}
//pulling products
if (mysql_num_rows($order) > 0){
while($row = mysql_fetch_array($order)){
$array[] = $row;
}
} else { echo "<div style='font-size:12px;'>No orders yet</div>";}
echo json_encode($array);
它拉1查詢,但無法從PHP文件中獲取另一個查詢
jQuery的
$.ajax({
type: "POST",
url: "order_load.php",
data: {order : thisId},
dataType:"json",
success: function(data){
$.each(data, function(i, val){
var append2 = '<div class="product">';
append2 +='<div class="view_left2">';
append2 +='<b>Item ID:</b> ';
append2 +='#'+val.id;
append2 +='</div>';
append2 +='<div class="line"><img src="images/productLine.png" /></div>';
append2 +='<div class="viewleft3">'+val.desc+'</div>';
append2 +='<div class="right_order">';
append2 +='<div class="line"><img src="images/productLine.png" /></div>';
append2 +='<div class="view_right2">';
append2 +='<div class="price3">$'+val.amount+'</div></div><div class="clear"></div></div>';
append2 +='<div class="clear"></div></div>';
$(".view_product2").append(append2);
});
這是我的json輸出:
[{"0":"1","paid":"1"},{"0":"336","id":"336","1":"1","qty":"1","2":"sdfgsdf","desc":"sdfgsdf","3":"yes","gst":"yes","4":"44","price":"44","5":"44.00","amount":"44.00","6":"225","order_id":"225"}]
您的代碼有幾處錯誤。 首先; 您從返回的json .amount
引用了一個不存在的json屬性。 我已將其更改為.price
以返回正確的結果。
其次..
您返回的json是對象數組。 若要訪問.paid
屬性,您需要先引用數組的第一項,然后才能訪問和設置paid
變量。
var paid = data[0].paid; // set the paid variable per its placement in the json
$.each(data, function (i, val) {
if (i != 0) { // check to make sure it isn't the first object of the array
var append2 = '<div class="product">';
append2 += '<div class="view_left2">';
append2 += '<b>Item ID:</b> ';
append2 += '#' + val.id;
append2 += '</div>';
append2 += '<div class="line"><img src="images/productLine.png" /></div>';
append2 += '<div class="viewleft3">' + val.desc + '</div>';
append2 += '<div class="right_order">';
append2 += '<div class="line"><img src="images/productLine.png" /></div>';
append2 += '<div class="view_right2">';
append2 += '<div class="price3">$' + val.price + '</div></div><div class="clear"></div></div>';
// ^ use the correct json property to access the value. It is not amount.
append2 += '<div class="clear"></div></div>';
$(".view_product2").append(append2);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.