gpt4 book ai didi

php - 无法在 jquery 中访问或打印 Ajax 响应

转载 作者:行者123 更新时间:2023-12-01 04:41:07 24 4
gpt4 key购买 nike

我从 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"}

如何打印响应并将数据放入表格中?感谢您的帮助!

最佳答案

对于与查询匹配的每条记录,您正在回显一个有效的 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:在回波之前测试边界条件,例如。未找到与查询匹配的记录,以及服务器端软件中可能潜藏的其他异常情况。

关于php - 无法在 jquery 中访问或打印 Ajax 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37526346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com