【问题标题】:Laravel: Ajax error, can't figure out how to set the right URLLaravel:Ajax 错误,无法弄清楚如何设置正确的 URL
【发布时间】:2018-04-15 10:35:38
【问题描述】:

现在我遇到了 Ajax 问题。过去 3 个小时我一直在用 Google 搜索,但无法弄清楚。基本上我希望我的表单在不重新加载页面的情况下提交。简单的 Ajax 对吧?仍然不适合我:(

这是我的代码:

$('#counter').submit(function(event){
    event.preventDefault();
    $.ajax({
        type: 'POST',
        url: '/games/question/update',
        data: $('form#counter').serialize(),
        dataType: 'json'
        // key: value
    }).done(function(data) {
        console.log(data);
    });
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    return false;
});

我的路线:

Route::group(['prefix' => 'games', 'as' => 'games.'], function () {
Route::get('/', 'GamesController@index')->name('index');
Route::get('/winner', 'GamesController@winner');
Route::put('/question/update', 'GamesController@update');
Route::get('/question/{id}/', 'GamesController@counter');
Route::post('/', 'GamesController@store')->name('store'); });

我的表单如下所示:

<form method="POST" action="{{ route('games.update', $player->id) }}" id="counter"> ... </form>

我需要使用 ajax 提交此表单,因为我在同一页面上有第二个表单..

一般来说,你可能会告诉我 Laravel 和 php 的新手,如果你需要其他任何东西,这里是我的项目的 git repo:

https://github.com/dirtypaulmfz/Quiztopher.git

感谢您的帮助! :)

【问题讨论】:

    标签: php ajax laravel


    【解决方案1】:

    这是由于form method spoofing。当遇到使用getpost 的路由时,您需要设置_method 参数。您的表单数据应包括:

    _method: 'patch' // or put
    

    有一个helper method

    {{ method_field('patch') }}
    

    还有一个刀片指令:

    @method('put')
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2019-10-26
      • 1970-01-01
      • 2019-03-12
      • 2015-10-26
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多