使用ajax从路由中调用删除URL?

时间:2017-07-12 08:34:57

标签: ajax laravel laravel-5

如何使用ajax从路线调用网址?

路线:

Route::delete('dashboard/tags/destroy/{tag}', 'TagCon@destroy')->name('tagdestroy');

控制器:

public function destroy($id) {
        $tag = Tag::findOrFail($id);
        $tag->delete();

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

Ajax代码:

$(document).on('click', '.delete-modal', function () {
        $('.modal-title').text('Delete');
        $('#id_delete').val($(this).data('id'));
        $('#title_delete').val($(this).data('title'));
        $('#deleteModal').modal('show');
        id = $('#id_delete').val();
    });
    $('.modal-footer').on('click', '.delete', function () {
        $.ajax({
            type: 'DELETE',
            url: 'dashboard/tags/destroy/' + id,
            data: {
                '_token': $('input[name=_token]').val(),
            },
            success: function (data) {
                toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
                $('.item' + data['id']).remove();
                $('.col1').each(function (index) {
                    $(this).html(index + 1);
                });
            }
        });
    });

它没有做任何可能因为它没有调用正确的路线?但是,如果我将此url: 'dashboard/tags/destroy/' + id,更改为此url: '{{ URL::route('tagdestroy') }}' + id,,则会返回错误Missing required parameters for [Route: tagdestroy] [URI: dashboard/tags/destroy/{tag}]

代码的错误部分在哪里?感谢

解决

立即开始工作,将ajax函数中的url调用更改为url: 'tags/destroy/' + id,而不是url: 'dashboard/tags/destroy/' + id,。我不知道为什么它有效,删除方法网址仍然定义为Route::delete('dashboard/tags/destroy/{tag}', 'TagCon@destroy')->name('tagdestroy');,而不是Route::delete('tags/destroy/{tag}', 'TagCon@destroy')->name('tagdestroy');

3 个答案:

答案 0 :(得分:0)

'{{ URL::route('tagdestroy',[Your Params ]) }}

您在指定路线中缺少参数。

答案 1 :(得分:0)

我认为第一个网址运行良好。 你仔细检查了id参数吗? 我在ajax函数中看到,你没有声明它。 你用不同的函数调用id

答案 2 :(得分:0)

你的uri标签是否必要?我用它在我的ajax调用中省略它,将它用作POST参数。 路线:

Route::delete('dashboard/tags/destroy', 'TagCon@destroy')->name('tagdestroy');

Ajax电话:

$(document).on('click', '.delete-modal', function () {
    $('.modal-title').text('Delete');
    $('#id_delete').val($(this).data('id'));
    $('#title_delete').val($(this).data('title'));
    $('#deleteModal').modal('show');
    id = $('#id_delete').val();
});
$('.modal-footer').on('click', '.delete', function () {
    $.ajax({
        type: 'DELETE',
        url: '{{route('tagdestroy')}}',
        data: {
            '_token': $('input[name=_token]').val(), 'id': id
        },
        success: function (data) {
            toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
            $('.item' + data['id']).remove();
            $('.col1').each(function (index) {
                $(this).html(index + 1);
            });
        }
    });
});

控制器:

public function destroy() {
    $id = e(Input::get('id'));
    $tag = Tag::findOrFail($id);
    $tag->delete();
    return response()->json($tag);
}
相关问题