如何使用jQuery和Laravel以及 AJAX 来根据用户选择的运输服务更新div的价格?

b5buobof  于 2023-06-05  发布在  jQuery
关注(0)|答案(1)|浏览(200)

我输入选择如下:

<div class="mb-4 pb-2">
       <select class="form-select" id="shipment-price" required
       @if(Cart::content()->isEmpty()) disabled @endif>
          <option value="" disabled selected style="display: none;">- Select Delivery Service -</option>
       @forelse ($shipment as $shipping)
          <option value="{{ $shipping->id }}">{{ $shipping->name }} ({{ presentPrice($shipping->price) }})</option>
       @empty
          <option value="0">-</option>
       @endforelse
       </select>
    </div>

和div像这样

<div class="row justify-content-between">
       <div class="col">
           <p class="mb-1"><b>Shipping</b></p>
       </div>
       <div class="flex-sm-col col-auto">
           <p class="mb-1"><b id="shipping-value">Rp. 0</b></p>
       </div>
   </div>

我想更新div价格以使用用户选择的装运服务
反相0
当使用者选择托运服务时,有人可以帮助我吗??

6bc51xsx

6bc51xsx1#

onChangeshipment-price,您将有一个路由返回shipment value

$(document).ready(function(){
        $('#shipment-price').on('change', function(e){ //on change of shipment-price 
        let shipmentValue = $('#shipment-price').val(); // the dropdown item selected value
        $.ajax({
            type : "GET",
            dataType : 'json', 
            url : "{{route('pricevalue', ['id'=>"+shipmentValue+"])}}",
            success : function(data){
                console.log(data);
                if(data.status){ //from your response 
                    $('#shipping-value').val(data.amount) // you can check the console to be sure of the response  
                }
            },error: function(e){
                console.log(e);
            },
        })
    });
})

您的路线将如下所示:

Route::get('/get-shipment-price/{id}', [ShipmentController::class, 'getShipmentPrice'])->name('pricevalue');

YourController中的getShipmentPrice函数看起来像:

public function getShipmentPrice(Request $request)
    {
        $shipmentPrice = Shipment::where('shipment-type', $request->id)->first();
        if ($shipmentPrice) {
            return response()->json([
                'status' => true,  'data' => $shipmentPrice
            ]);
        }
        return response()->json([
            'status' => false, 'message' => 'Error',
        ]);
    }

相关问题