【问题标题】:After form submit it redirects to same page表单提交后重定向到同一页面
【发布时间】:2017-12-28 14:45:50
【问题描述】:

我正在尝试使用 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');
});

项目控制器

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-显示第一个 2-第二个不显示,toastr也不显示

我什至尝试添加一个链接并触发重定向到索引页面的点击功能,但它不起作用

有什么帮助吗?

【问题讨论】:

    标签: php jquery ajax laravel-5.5


    【解决方案1】:

    假设你有类似的形式

    <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
    });
    

    它将停止提交按钮的默认行为。

    【讨论】:

    • 或者使按钮类型="button"
    • 好的,现在页面没有向 URL 添加变量,但我仍然有一个问题:我添加了一个锚点: 成功后我添加了: $('#aftersave').click();为什么它不起作用?
    • @Guest012393 .click().on('click', function() {}) 的快捷方式。要发出点击,请使用.trigger('click')
    • @Guest012393 是的,我不知道由于安全原因它不会工作。但是你可以阅读Jquery how to trigger click event on href element
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多