我通过 Ajax 将幻灯片(Jquery Ui Slider)中的每个 slider 值获取到我的 Controller 。
Slider + Ajax 看起来像这样:
$("#sliderNumCh").slider({
range: "min",
min: 0,
max: 20,
step: 1,
value: numbersOfChapters,
change : function(e, slider){
$('#sliderAppendNumCh').empty();
var sliderValue = slider.value;
var getSliderVal = document.getElementById('sliderValue').value = sliderValue;
var getPrId = document.getElementById('editId').value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: {
value: getSliderVal,
productId : getPrId
},
success: function (option) {
console.log(getSliderVal);
}
});
},
});
所以我脑子里确实有这个:
<meta name="csrf-token" content="{{ csrf_token() }}">
我的路线是这样的:
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController@editProductPost']);
在我的 Controller 方法中,我这样调用它:
public function editProductPost(Request $request)
{
$sliderValue = $request->get('value');
Log::info($sliderValue);
return view('productRom.edit', [
'sliderValue' => $sliderValue
]);
}
Log::info($sliderValue) 告诉我,我在每张幻灯片上都得到了正确的 slider 值。
当我尝试返回到我的编辑 View 时,我在控制台中收到此错误:
POST http://localhost/myApp/public/product/edit/73 500 (Internal Server Error)
我该如何解决这个问题?
编辑
因为在我看来有这条线:
<form action="{{ route($route) }}"...>
没有定义路由变量,所以我在返回语句中添加了它。
return view('productRom.edit', [
'sliderValue' => $sliderValue,
'route' => 'editProductPost'
]);
错误消失了,但是当我尝试像这样访问 $sliderValue
变量时:
<p>{{ isset($sliderValue) ? $sliderValue : "nothing" }}</p>
它打印nothing
编辑
Controller :
public function editProductPost(Request $request)
{
return response()->json([
'sliderValue' => $request->get('value')
]);
}
View (ajax):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: {
value: getSliderVal,
productId : getPrId
},
success: function (response) {
// check it has some data
if (response.length) {
// spit it out
console.log(response);
} else {
console.log('nothing returned');
}
}
});
最佳答案
你的 Controller 方法应该是这样的:
public function editProductPost(Request $request)
{
return response()->json([
'sliderValue' => $request->get('value')
]);
}
您不应该向 ajax 请求返回 View 。
您的 ajax 成功方法应该如下所示(例如):
// first arg is the data returned by the controller method
success: function (response) {
console.log(response);
}
它应该输出这样的东西:
{
'sliderValue': 4
}
关于javascript - Ajax Laravel 返回 View 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38475451/