【问题标题】:How to insert data using ajax with id and without using forms in laravel如何使用带有id的ajax插入数据而不使用laravel中的表单
【发布时间】:2021-05-11 01:58:05
【问题描述】:

我尝试像这样在我的 url 中使用 id 插入数据。

<a href="{{route('absent',$User->id)}}">absent</a>                                                   
<a href="{{route('present',$User->id)}}">present</a>

我的路线是:

Route::get('/present/{id}', 'UserController@present')->name('present');
Route::get('/absent/{id}', 'UserController@absent')->name('absent');

路线正在运行。但是页面正在加载,我尝试在不加载的情况下插入数据。我知道如何使用 ajax HTML 表单方式插入数据。但是如何使用 ajax 使用 id 插入?

【问题讨论】:

  • 可以使用form,通过ajax提交

标签: ajax laravel


【解决方案1】:

如果您想在不重新加载的情况下插入数据,您必须将 JavaScript 函数绑定到您指定的 HTML 链接。 This example 不同,但您可以使用相同的方法来满足您的需求。

【讨论】:

    【解决方案2】:

    我建议您将锚标记更改为按钮并向它们添加一个类并将它们的路由端点保存在数据属性中:

    <button class="action_buttons" data-route="{{route('absent', $User->id)}}">absent</button>
    <button class="action_buttons" data-route="{{route('present', $User->id)}}">present</a>
    

    然后,使用 JQuery 事件处理来检测它们何时被点击,然后简单地使用 Ajax 从按钮的数据属性中获取相关路由并向该路由发送 GET 请求:

    $('.action_buttons').on('click', function(){
    
        // Get the route data from the tag.
        let route = $(this).data('route');
    
        $.ajax({
            url: route,
            type: 'GET',
            success: function(resp) {
                console.log(resp);
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 2021-01-01
      • 2015-02-26
      • 2019-09-25
      • 1970-01-01
      • 2021-05-10
      • 2018-06-23
      • 2022-11-25
      • 2016-06-23
      相关资源
      最近更新 更多