我收到了来自我的ajax电话的回复,但我该如何访问或至少打印回复?
这是我的ajax电话
$.ajax({
type: "POST",
url: '../backorderReport.php',
data: { from : from, to : to },
dataType: "JSON",
success: function(data){
console.log(data[0].orderID); //not printing anything
console.log(data); //not printing anything
}
});
这是我的php文件
$from = $_POST["from"];
$to = $_POST["to"];
$orders = $wpdb->get_results("SELECT * FROM wp_orderrecords WHERE orderDate BETWEEN '".$from."' AND '".$to."'");
foreach($orders as $order){
$orderID = $order->orderID;
$orderDate = $order->orderDate;
$status = $order->status;
$clientID = $order->clientID;
$bill = $order->bill;
$ship = $order->ship;
$pay = $order->pay;
$total = $order->total;
$results = $wpdb->get_results("SELECT * FROM wp_clients WHERE clientID = '".$clientID."%'");
foreach($results as $order){
$clientsName = $order->clientsName;
}
$c = str_replace(' ', " ", $clientsName);
$orderItem = array(
'orderID' => $orderID,
'orderDate' => $orderDate,
'orderStatus' => $status,
'clientsName' => $c,
'bill' => $bill,
'ship' => $ship,
'pay' => $pay,
'total' => $total
);
echo json_encode($orderItem);
}
我得到了这个回复
{"orderID":"26","orderDate":"2016-05-11","orderStatus":"Active","clientsName":"Pebbe\u00a0Kristel\u00a0A
\u00a0Bunoan","bill":"Billed","ship":"Delivered","pay":"Unpaid","total":"1200.00"}{"orderID":"27","orderDate"
:"2016-05-13","orderStatus":"Completed","clientsName":"Lovely\u00a0Carbon","bill":"Billed","ship":"Delivered"
,"pay":"Paid","total":"4650.00"}
如何打印响应并将数据放在表格中?谢谢你的帮助!
答案 0 :(得分:1)
对于与查询匹配的每条记录,您正在回显一个有效的json字符串。因此得到类似的东西:
{ record_1 } { record_2 }
这是无效的json。你想要一个像:
这样的数组[{ record_1 },{ record_2 }]
稍微修改一下你的php:
$from = $_POST["from"];
$to = $_POST["to"];
$orders = $wpdb->get_results("SELECT * FROM wp_orderrecords WHERE orderDate BETWEEN '".$from."' AND '".$to."'");
$records = []; // adds an array for the records
foreach($orders as $order){
$orderID = $order->orderID;
$orderDate = $order->orderDate;
$status = $order->status;
$clientID = $order->clientID;
$bill = $order->bill;
$ship = $order->ship;
$pay = $order->pay;
$total = $order->total;
$results = $wpdb->get_results("SELECT * FROM wp_clients WHERE clientID = '".$clientID."%'");
foreach($results as $order){
$clientsName = $order->clientsName;
}
$c = str_replace(' ', " ", $clientsName);
$orderItem = array(
'orderID' => $orderID,
'orderDate' => $orderDate,
'orderStatus' => $status,
'clientsName' => $c,
'bill' => $bill,
'ship' => $ship,
'pay' => $pay,
'total' => $total
);
$records[] = $orderItem; // push each order item on the array
}
echo json_encode($records); // echo the array
ps:测试回波前的边界条件,例如没有找到与查询匹配的记录,以及可能潜伏在服务器端软件中的其他奇怪信息。
答案 1 :(得分:0)
使用JSON.parse
success: function(data){
var parsedData = JSON.parse(data);
}
答案 2 :(得分:0)
你需要解析json字符串
success: function(data){
var resultArray = $.parseJSON(json);
console.log(resultArray[0].orderID);
console.log(resultArray);
}