我想做一个账单结构,我可以选择一个客户,下一个选择表格将显示客户的所有项目,但由于某种原因,我遇到了麻烦。
这是我的路线.php
Route::resource('bills', 'BillsController');
Route::get('bills/items','BillsController@items');
这是我的账单控制器
private function items($request) {
try {
if ($request) {
$id = $request->client_id;
$items = Item::where('client_id', $id)->get()->pluck('code', 'id');
return redirect()->json($items);
} else {
Session::flash('error_message', 'Ups! Hemos tenido un error.');
return redirect()->back();
}
} catch (Exception $e) {
Session::flash('error_message', 'Ups! Hemos tenido un error.');
return redirect()->back();
}
}
这是我的边栏选项卡中的脚本:
<script>
$(document).ready(function() {
$('#clients').change(function() {
var $client_id = $('#clients').val();
console.log($client_id);
var $url = '{{ url('MyAdmin/bills/items') }}';
console.log($url);
$.getJSON($url, {'client_id': $client_id}, function(resp) {
console.log(resp); //For some reason here the "resp" is not working
$.each(resp, function(key, answer) {
$('#items').append('<option value="'+answer.id+'">'+answer.code+'</option>');
});
});
});
});
知道吗?多谢!
那是
因为它实际上进入了} catch (Exception $e)
。但是您也不会在此处返回 JSON 响应。您正在重定向。
问题是 redirect()
对象不包含 ->json()
方法,但 response()
对象包含。所以改变它:
return response()->json($items);
此外,在您的错误处理程序中,在响应时返回一个422
错误代码,以便它会触发您的承诺.error()
。
return response(422)->json([$e->getMessage()]);