javascript - 如何使用 jquery 选择框更改计算总运费?
问题描述
所以系统是这样工作的。如果用户购买超过 500 美元,他们将获得免费送货费,否则将收取 10 美元的订单少于 500 美元。
所以我的问题是用户有两个选项可以选择接收他们的物品。一种是“自取”,一种是“外送”</p>
如何使我的系统根据下拉值更改计算总额的方式。因为如果用户选择“自取”,则运费应自动设置为 0 美元。
我现在用php进行了计算。所以当订单少于 500usd 时,它会自动在总价中增加 10usd。下面是计算的php代码。
while ($row = $query->fetch_assoc()) {
$seller_id = $row['seller_id'];
$product_id = $row['product_id'];
$quantity = $row['cart_qty'];
$quantity_unit = $row['cart_unit'];
$purchase_price = $row['cart_price'] * $quantity;
if($purchase_price < 500.00){
$grand_total += ($row['cart_price'] * $row['cart_qty'])+10.00;
}else{
$grand_total += $row['cart_price'] * $row['cart_qty'];
}
$order_status = 1;
$datetime = date('Y-m-d H:i:s');
如何根据我上面解释的问题使用 jQuery 选择框更改方法进行计算?
解决方案
当然没问题。这将是使用 AJAX 的示例:
我假设您的 HTML 看起来像这样:
<select name="delivery" id="delivery">
<option selected value="pickup">Pickup</option>
<option value="delivery">Delivery</option>
</select>
<p id="grand_total"></p>
那么你的 Javascript 看起来像这样(假设你已经包含了 JQuery)
$('document').ready(function(ev){
$('#delivery').on('change',function(ev2){
// get the value
var delivery = $(this).val();
// send to your php file using AJAX
$.get("URL TO YOUR PHP FILE?delivery="+delivery, function(data, status){
// Data contains your grand total you could now display it
$('#grand_total').html(data);
});
});
});
最后在这里你的PHP文件:
$delivery = $_GET['delivery'];
// I would add variable for this
$shipping_fee = 0;
while ($row = $query->fetch_assoc()) {
$seller_id = $row['seller_id'];
$product_id = $row['product_id'];
$quantity = $row['cart_qty'];
$quantity_unit = $row['cart_unit'];
$purchase_price = $row['cart_price'] * $quantity;
if($purchase_price < 500.00){
$shipping_fee = 10.00;
}else{
$shipping_fee = 0.00;
}
// Also Check for the delivery option here
if( $delivery == 'pickup')
{
// Shipping Fees should always be 0
$shipping_fee = 0.00;
}
// Finally do the calculation here
$grand_total += ($row['cart_price'] * $row['cart_qty'])+$shipping_fee;
}
$order_status = 1;
$datetime = date('Y-m-d H:i:s');
// For your ajax request print and return result
echo $grand_total;
return $grand_total;
推荐阅读
- c++ - C++ 继承具有自己的类内结构的模板类
- python - Django 中的 Slug 和日期字段问题的唯一问题
- reactjs - 您应该在什么级别检索数据?
- javascript - 页面加载的 Keyup 替代方案
- java - 如何检查两个集合是否包含相同的对象
- javascript - 如何手动触发或模仿guildMemberAdd
- mysql - MySQL - 自动递增字段中的重复值
- java - 将 EventBus 与 ViewPager 一起使用时,有时会出现“已添加片段”
- java - 如何将 grails 与 mysql 连接以及为什么 grails compile 显示:compileJava NO-SOURCE
- ignite - Apache Ignite 中的数据再平衡