我试图使用ajax实现一个简单的创建表单数据保存到数据库,但问题是提交后,页面重定向到相同的URL,其中添加了变量示例:localhost/items/create?_token=1r42dIWXc4oirlJ2gGbEWgZL1I32L6FefVdmy3zy&_token=1r42dIWXc4oirlJ2gGbEWgZL1I32L6FefVdmy3zy&txtName=kjsjksjksk&txtAmount=8202
web.php
Route::group(['middleware' => ['web']], function(){
Route::get('/items', 'ItemController@index')->name('items');
Route::get('/items/create', 'ItemController@create')->name('itemcreate');
Route::POST('/items/store', 'ItemController@store')->name('itemstore');
});
ItemController
public function create()
{
$customers = \App\Customer::all();
return view("items.create")->with('customers', $customers);
}
public function store(Request $req)
{
$item = new \App\Item;
$item->name = $req->name;
$item->details = $req->details;
$item->total_amount = $req->total_amount;
$item->customer_id = $req->customer_id;
$item->save();
return ['redirect' => route('items')];
}
create.blade.php
$.ajax({
type: 'POST',
url: 'store',
data: {
'_token': $('input[name=_token]').val(),
'name': $('input[name=txtName]').val(),
'details': $('textarea#txtDetails').val(),
'total_amount': $('input[name=txtAmount]').val(),
'customer_id': $('#customer').val(),
},
success: function (data){
//window.location = response.data.redirect;
alert("success");
// toastr.success('Workshop added successfully');
// setTimeout(function(){
alert("after timeout");
// }, 1000);
}
});
注意成功功能中的警报:1-显示第一个 - 第二个不显示,也不显示toastr
我甚至尝试添加一个链接并触发重定向到索引页面的单击功能,但它不起作用
有帮助吗?
假设你有类似的形式
<form action="someAction" method="POST">
<input.../>
<button id="button" type="submit"...>Submit</button>
</form>
你使用onclick
事件。例如
$('#button').on('click', function() {
//your code
});
现在你可以在event
中传递function()
作为参数并使用preventDefault()
方法。例:
$('#button').on('click', function(event) {
event.preventDefault();
//your code
});
它将停止提交按钮的默认行为。