如何在laravel 5.6中使用ajax编辑表单

时间:2018-06-03 13:36:44

标签: ajax laravel-5.6

我在使用laravel 5.6和ajax时遇到了ajax 404错误,我无法弄清楚原因。

我想通过点击带有ajax的链接来更新状态从0到1,但它在控制台中给出了错误404.

web.php

Route::resource('peoples', 'PeopleController');
Route::get('/read', 'PeopleController@read');

AJAX

function load() {
            $.get('/read', function (data){
                $.each(data, function (key, val) {
                    $('#data').append("<tr>"+
                        "<td>"+val.id+"</td>"+
                        "<td id='ename'>"+val.name+"</td>"+
                        "<td id='eaddress'>"+val.address+"</td>"+
                        "<td id='ecountry'>"+val.country+"</td>"+
                        "<td>"+
                            "<button class='btn btn-warning' id='edit' data-id="+val.id+">Edit</button>"+
                            "<button class='btn btn-danger'>Delete</button>"
                        +"</td>"+
                    +"</tr>")
                })
            })
        }

        load();

        $(document).on('click', '#UpdateForm', function () {
            id = $(this).data('id');
            name = $('#name').val();
            address = $('#address').val();
            country = $('#country').val();
            $.post("{{ URL('peoples/"+id+"/update') }}", {name:name, address:address, country:country, id:id}, function (data){
                $('#data').html('');
                load();
            });
        });

控制器

public function update(Request $request, People $people)
    {
        if($request->ajax()) {
            $request->validate([
                'name' => 'required',
                'address' => 'required',
                'country' => 'required',
            ]);

            $people = People::find($request->id);
            $people->name = $request->name;
            $people->address = $request->address;
            $people->country = $request->country;
            $people->save();

            return response()->json();
        }
    }

404 Error

0 个答案:

没有答案