php - 如何使用AJAX从select中获取数据以及如何返回值
问题描述
我创建了一个短代码,其中包含一个填充有 woocommerce 产品 ID 和标题的下拉列表,我想做的是在表格中显示数据。我还有一个查询来从数据库中获取数据。我试图创建一个 AJAX jQuery 脚本来从下拉列表中的选定项目中获取数据,但它不起作用。
$the_query = new WP_Query( array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby'=> 'title',
'order' => 'ASC',
));
ob_start();
<select id="product_id" name="product_id" method= "POST" >
<option value="0"><?php echo ("Select session"); ?></option>
<?php
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<option name= "product_option" value="'.get_the_ID().'">#'. get_the_ID().' '. get_the_title().'</option>';
?>
<?php
}
}
?>
</select>
<?php
$prod_id = $_POST['selectedValue'];
echo $prod_id;
if (! empty($prod_id)) {
$allOrders = retrieve_orders_ids_from_a_product_id($prod_id);
?>
<table id="registration_table">
<tr>
<th> Order number </th>
<th> Name </th>
<th> Status </th>
<tr>
<?php
if ( $allOrders ) {
foreach ($allOrders as $orderID ) {
$order = wc_get_order( $orderID );
$order_data = $order->get_data(); // The Order data
?>
<tr>
<td> <?php $order_data["id"]; ?> </td>
<td> <?php $order_data["billing"]["first_name"]?> <?php $order_data["billing"]["last_name"]; ?> </td>
<td> <?php $order_data["status"] ?> </td>
<tr>
<?php
}
}
?>
</table>
}
$content = ob_get_clean();
return $content;
我对数据库的查询
$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
$orders_ids = $wpdb->get_col( "
SELECT DISTINCT woi.order_id
FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p
WHERE woi.order_item_id = woim.order_item_id
AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses )
AND woim.meta_key LIKE '_product_id'
AND woim.meta_value LIKE '$prod_id'
ORDER BY woi.order_item_id DESC"
);
return $orders_ids;
jQuery("#product_id").on('change', function(){
console.log("list item selected");
var val = jQuery(this).val();
console.log(val);
//Ajax call to php for result
jQuery.ajax({
type: 'POST',
url: '/scanner',
data: { val: val},
success: function (resp) {
console.log(resp
},
error: function (err) {
console.log(err)
},
complete: function () {
console.log("Task Complete");
}
});
});
解决方案
推荐阅读
- javascript - 将firebase中的集合转换为nodejs中的数组
- flutter - 如何使用 Firestore 绘制 gridview 卡片组件背景
- c# - 绘制具有相对位置和比例的三角形
- javascript - 引用类型本身,TypeScript
- sql - SUM() 正在计算所有值,而不是满足条件的值
- bash - 如何在用户输入的循环中运行 f(x)
- django - 同一视图中的条件执行
- java - SpringBoot:如何将蛇案例转换为骆驼案例
- laravel - Laravel Vue.js 在 ./resources/js/app.js 中构建错误
- netcdf - 如何在 NCO 中按经度裁剪 NetCDF 文件