我正在使用Laravel 5.6。我想更新数据,使用ajax选择下拉列表。我有两个带外键的数据库。我也使用ajax以创建形式制作选定的产品,它可以工作。但是,当我以更新形式使用它时,它不起作用。
这是我的代码:
web.php
Route::resource('admins/order', 'NotifController');
Route::get('admins/order/ajax/{id}', 'NotifController@withAjax');
控制器
public function edit(Order $order)
{
$produks = Produk::pluck('nama_produk', 'id');
return view('admins/order/edit', compact('order', 'produks'));
}
public function withAjax($id){
$items = Item::all()
->where('id_produk',$id)
->pluck('nama_item','id');
return json_encode($items);
}
public function update($id, Request $request)
{
$order = Order::findOrFail($id);
$data = $request->all();
if($request->hasFile('filebrief')){
$exist = Storage::disk('foto')->exists($order->filebrief);
if(isset($order->filebrief) && $exist) {
$delete = Storage::disk('filebrief')->delete($order->filebrief);
}
$filebrief = $request->file('filebrief');
if($request->file('filebrief')->isValid()){
$file_name = date('YmdHis') . ".pdf";
$upload_path = 'filebrief';
$request->file('filebrief')->move($upload_path, $file_name);
$data['filebrief'] = $file_name;
}
}
$order->update($data);
Session::flash('flash_message', 'Data Berhasil Diperbarui.');
return redirect('admins/order');
}
这是我的表单编辑代码:
<div class="form-group">
<label for="title">Pilih Produk :</label>
<select name="id_produk" class="form-control" style="width:350px">
<option value="">- Produk -</option>
@foreach ($produks as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
</select>
</div>
@if ($errors -> any())
<div class="form-group {{ $errors -> has('id_item') ? 'has-error' : 'has-success' }}">
@else
<div class="form-group">
@endif
<label for="title">Pilih Item :</label>
<select name="id_item" class="form-control" style="width:350px">
<option value="">- Item -</option>
</select>
@if ($errors -> has('id_item'))
<span class="help-block">{{ $errors -> first('id_item') }}</span>
@endif
这是用于表单编辑(下拉)的js代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="id_produk"]').on('change', function() {
var produkid = $(this).val();
if(produkid) {
$.ajax({
url: 'admins/order/ajax/'+produkid,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="id_item"]').empty();
$.each(data, function(key, value) {
$('select[name="id_item"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="id_item"]').empty();
}
});
});
</script>
为什么不起作用?