php - 如何在 laravel 6 中使用 ajax 更新(放置)而不刷新?
问题描述
我正在尝试更新我的数据,而无需每次都使用 ajax 刷新页面。我过去并没有真正使用过ajax,所以这对我来说很新。我已经尝试了一些与我见过的示例不同的方法,这就是我现在可以整理的。
目前它给了我一个错误The PUT method is not supported for this route.
,上面的网址保持不变。
这是我目前尝试过的:
刀
<div class="table">
<div class="tr">
<span class="td">Name</span>
<span class="td">New cases</span>
<span class="td">cases</span>
<span class="td">deaths</span>
<span class="td">recoveries</span>
<span class="td">Submit</span>
</div>
@foreach($data as $dat)
<form class="tr" id="form{{$dat->id}}">
<input type="hidden" value="{{ csrf_token() }}" id="csrf_token" />
<input type="hidden" name="id" value="{{$dat->id}}">
@method('put')
<span class="td"><input type="text" name="name" value="{{$dat->country_name}}"/></span>
<span class="td"><input type="text" name="nCases" value="{{$dat->new_cases}}"/></span>
<span class="td"><input type="text" name="cases" value="{{$dat->cases}}"/></span>
<span class="td"><input type="text" name="deaths" value="{{$dat->deaths}}"/></span>
<span class="td"><input type="text" name="recoveries" value="{{$dat->recoveries}}"/></span>
<span class="td"><input type="submit" name="submit" value="Submit"/></span>
</form>
@endforeach
</div>
下面的脚本
<script>
$('form').submit(function( event ) {
event.preventDefault();
$.ajax({
action: {{url("/ajaxtest")}},
type: 'put',
data: $('form').serialize(),
dataType: 'json',
success: function(response){
console.log(response);
},
error: function( _response ){
// Handle error
}
});
});
</script>
控制器
public function ajaxTest(Request $request) {
$id = \Request::input('id');
$cases = \Request::input('cases');
$nCases = \Request::input('nCases');
$deaths = \Request::input('deaths');
$recoveries = \Request::input('recoveries');
Countries::where("id", $id)->update([
'cases' => $cases,
'deaths' => $deaths,
'new_cases' => $nCases,
'recoveries' => $recoveries
]);
}
路线
Route::put('/ajaxtest', 'CountriesController@ajaxTest');
解决方案
好的,你@method("put")
的刀片中有,所以当你序列化表单时,这个输入值已经在你的数据中:
// serialized data looks like
{
...
"_method": "put"
}
您需要的只是将 ajax 类型从put
to更改为post
,这有帮助
此外,您不必@csrf
在每种形式中都有,只需为页面输入 1 个并将其值设置为您的 ajax 标题
// in blade
<input type="hidden" value="{{ csrf_token() }}" id="csrf_token" />
// in js
$('form').submit(function( event ) {
event.preventDefault();
let token = $("#csrf_token").val();
$.ajax({
action: {{url("/ajaxtest")}},
type: 'post', // CHANGE this line from put to post
headers: { 'X-CSRF-TOKEN': token }, // ADD token to headers
data: $(this).serialize(), // serialize the form submitted
dataType: 'json',
success: function(response){
console.log(response);
},
error: function( _response ){
// Handle error
}
});
});
推荐阅读
- typescript - typescript 的可区分联合可以与条件类型一起使用吗?
- python - 如果数据帧的值属于同一区间,则将数据帧的值替换为区间的上限
- c# - Selenium:更改 Tor 电路
- python - Revit Sketched Stair Using Python:仅适用于一级
- typescript - 无法从 Deno 中的请求中销毁值(Typescript)
- c# - 自定义响应消息 JSON Web Api c#
- java - 是否可以在java中将增量运算符从int转换为long?
- c++ - 为链表预分配内存
- lua - 删除嵌套表中的重复表。卢阿
- git - 分离两个不同 git 帐户的 git 凭据