首页 > 解决方案 > 通过Ajax价格数据来形成输入文本,而不是选择产品的价格,而是总是带第一个价格

问题描述

我准备了一个销售记录表,您首先选择产品/库存名称。一旦做出此选择,它应该使用应该从数据库中的库存表中获取的该产品/股票的价格填充下面名为 unit_sales price 的字段。发生这种情况的部分原因是第一个库存/产品的价格被获取并且只出现在浏览器控制台中。帮助我获取特定产品的价格,并使其不仅出现在控制台中。我附上了一张数据库图片。

创建.blade.php

@extends('layouts.app')

@section('content')
    <br>
    <h1>Add Sale</h1>
    {!! Form::open(['action' => 'SalesController@store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}

    <div class="form-group">
    <label >Product Name</label>
    <select name="product_name" class="form-control" id="stock_name">
        <option>Select Product Name</option>
        @foreach ($stocks as $stock)
            <option value="{{ $stock->stock_name }}" >{{ $stock->stock_name}}</option>
        @endforeach
    </select>
</div>

<script>
    $(document).ready(function() {
        $("#stock_name").on('change', function () {
            let element = $(this);
            $.ajax({
                url: '/sales-price/getunitsellingprice',
                method: 'GET',
                data: {
                    'stock_name' : element.val(),
                },
                success: function (response) {
                       $("#unit_selling_price").val(response);
                },
            });
        });
    });
</script>

<div class="form-group">
    {{Form::label('unit_selling_price', 'Unit Selling Price')}}
    {{Form::text('unit_selling_price', '', ['class' => 'form-control', 'placeholder' => 'Unit Selling Price', 'id' => 'unit_selling_price'])}}
</div>
@endsection

销售控制器.php

public function getUnitSellingPrice(Request $request)
    {
        $stock_name = $request->input("stock_name");
        if($stock_name = null){
            return null;
        }
        $stock = Stock::where('stock_name', 'like', "%".$stock_name."%")->first();
        if ($stock == null) {
            return null;
        }
        return response()->json($stock->unit_selling_price);
    }

DB截图:股票表

https://slack-files.com/TP02E38GN-FP2G2BM2S-5cb95174a0

表格截图

https://slack-files.com/TP02E38GN-FP287UP55-0e4b4a0261

标签: phpajaxlaravelphp-7laravel-5.8

解决方案


您可以在此处省略触发器。并像这样重写这一行

$("#unit_selling_price").val(response.data);

还要获得您必须使用的选定选项值

let element = $(this+' :selected');

推荐阅读