duanke2503 2016-04-22 13:38
浏览 80
已采纳

使用ajax调用更新数据库onclick

I want to be able to update the database when I click on a li item but I am having a hard time to find an answer to this question. I know there are hundreds of similar questions but I haven't been able to get an answer specific to my question, for use with laravel.

This is my route for updating the database:

Route::post('api/tasks/update/{id}', function($id) {
    $task = App\Task::find($id);

    $task->completed = Request::get('completed');

    $task->save();
});

I just have an unordered list with some li's on my view, and once clicked on one of those views, I want to set a specific value in the database to either 0 or 1.

Here is my database table for tasks:

CREATE TABLE IF NOT EXISTS `tasks` (
  `id` int(10) unsigned NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `completed` tinyint(1) NOT NULL DEFAULT '0'
)

As you can see it is a simple id field, name field and completed field. My view:

<ul>
    @foreach($tasks as $task)
        <li>{!! $task->name !!}</li>
    @endforeach
</ul>

So I basically only need a pointer in the right direction for the actual AJAX call.

  • 写回答

1条回答 默认 最新

  • dqmhgz5848 2016-04-22 14:02
    关注

    I would recommend you use a GET request, to make a call ajax, first bind the id to the li element

    @foreach($tasks as $task)
        <li data-id='{!! $task->id !!}'>{!! $task->name !!}</li>
    @endforeach
    

    and use this jQuery function:

    $(document).ready(function(){
        $('li').on('click', function(e){
            $.ajax({
                url: 'api/tasks/update/'+$(this).data('id'),
                method: 'GET'
            }).then(function(){
                alert('success');
            });
        }); 
    })
    

    and finally, change your route from post to get.

     Route::get(...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条