[英]passing data from laravel view to controller via ajax onchange event
我在刀片視圖中有一個下拉列表。 我想立即將所選項目的值發送到控制器。 我在 web.php 中有 2 條路線:
Route::get('/plots', 'PlotController@index');
Route::get('/plots/{testId}', 'PlotController@getData');
第一個填充下拉列表。 第二個應該將下拉列表的值發送到控制器,控制器從 mysql 中提取內容並將數據發送回繪制圖表的視圖。 我可以讓下拉列表填充正常,但我不知道如何將選定的值發送到控制器。 我正在嘗試使用 ajax 這樣做:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
testId 輸出到控制台是正確的,但它永遠不會到達控制器。 我在控制台中看到的錯誤是:
獲取http://homestead.test/plots/1 500(內部服務器錯誤)
我對 laravel 很陌生,發現它非常令人困惑。 任何人都可以解釋這樣做的正確方法嗎?
編輯:在測試並確認 Rian 的答案正確后,我嘗試實現真正的代碼,這當然要復雜得多。 而不是控制器返回輸入 test_id:
return $request->test_id;
它實際上返回一個更復雜的結構:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
當我取消注釋原始控制器代碼(包括上面的返回部分)時,似乎會影響控制器返回任何內容的能力。 這是 PlotController getData 方法的前幾行:
public function getData(Request $request) {
Log::debug("made it to PlotController.php@getData");
Log::debug("test_id="+$request->testId);
這是日志輸出:
[2020-02-23 16:43:52] laravel.DEBUG:到 PlotController.php@getData
第二行不輸出任何內容。 這是我從下拉列表中選擇一個項目后在 javascript 控制台中看到的內容:
testId=49 jquery.min.js:2 GET http://homestead.test/get-data-by-id?test_id=49 500(內部服務器錯誤)
有任何想法嗎?
最簡單的方法是在Laravel Request
獲取數據。 至少我是這樣做的。
所以你的路線不應該包含任何參數。
您的路線將如下所示:
Route::get('get-data-by-id', 'PlotController@getData')->name('get.data.by.id');
你的ajax應該是這樣的:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
在控制器的getData()
函數中,只需使用Laravel Request
來獲取數據。
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
讓它更容易從 Get 發布
在 Web.php
Route::post('/list/plots', 'PlotController@getData')->name('getData');
在 Blade 文件 Ajax 請求中:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
在控制器:
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
嘗試這個。 希望對你有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.