如何用jQuery、Laravel和Ajax根据用户选择的配送服务更新Div价格?
实现方案
方法一:前端直接读取预存价格(简单快捷)
先修改你的<option>标签,给每个配送选项加个data-price属性,把格式化好的价格存进去,避免解析文本的麻烦,稳定性更高:
@forelse ($shipment as $shipping) <option value="{{ $shipping->id }}" data-price="{{ presentPrice($shipping->price) }}"> {{ $shipping->name }} ({{ presentPrice($shipping->price) }}) </option> @empty <option value="0">-</option> @endforelse
然后在页面底部(或单独的JS文件)添加这段代码,监听选择变化并更新价格:
// 获取页面元素 const shipmentSelect = document.getElementById('shipment-price'); const shippingValue = document.getElementById('shipping-value'); // 监听选择框的变化事件 shipmentSelect.addEventListener('change', function() { const selectedOption = this.options[this.selectedIndex]; // 从data-price属性取价格,没有则显示默认的Rp. 0 const price = selectedOption.dataset.price || 'Rp. 0'; shippingValue.textContent = price; });
要是不想修改option标签,也可以直接解析选项文本里的价格(不推荐,文本格式变动会导致失效):
shipmentSelect.addEventListener('change', function() { const selectedText = this.options[this.selectedIndex].text; // 提取括号内的价格内容 const priceMatch = selectedText.match(/\((.*?)\)/); const price = priceMatch ? priceMatch[1] : 'Rp. 0'; shippingValue.textContent = price; });
方法二:调用后端接口获取价格(安全可靠)
如果担心前端数据被篡改,或者需要实时从后端获取最新价格,用这种方式:
- 先在Laravel的
web.php路由文件中添加一个接口路由:
Route::get('/shipping-price/{id}', function($id) { $shipping = \App\Models\Shipping::findOrFail($id); return response()->json([ 'price' => presentPrice($shipping->price) ]); });
- 替换JS代码为以下内容,通过AJAX请求后端获取价格:
const shipmentSelect = document.getElementById('shipment-price'); const shippingValue = document.getElementById('shipping-value'); shipmentSelect.addEventListener('change', function() { const shippingId = this.value; // 未选中有效选项时显示默认价格 if (!shippingId || shippingId === '0') { shippingValue.textContent = 'Rp. 0'; return; } // 发送请求到后端接口 fetch(`/shipping-price/${shippingId}`) .then(res => res.json()) .then(data => { shippingValue.textContent = data.price; }) .catch(err => { console.error('获取价格出错:', err); shippingValue.textContent = 'Rp. 0'; }); });
内容的提问来源于stack exchange,提问作者Reynaldo
相关产品推荐
相关产品推荐

