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(...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?