简体   繁体   English

通过 AJAX 调用 Laravel 路由得到错误的 URL 404(未找到)

[英]Laravel Route call via AJAX gets wrong URL 404 (Not Found)

I have the following route defined in my web.php我在 web.php 中定义了以下路由

Route::delete('/contributions/contribution/destroy', 'ContributionController@destroy');

In my blade file I have a button that when clicked displays a sweetalert to confirm deletion.在我的刀片文件中,我有一个按钮,单击该按钮时会显示一个提示以确认删除。 This works correctly, but when the user presses the delete button instead of it going to the URL defined in Ajax it goes to an incorrect URL and logs the following error:这可以正常工作,但是当用户按下删除按钮而不是转到 Ajax 中定义的 URL 时,它会转到不正确的 URL 并记录以下错误:

jquery.min.js:4 DELETE http://localhost/contributions/batches/batch/edit 404 (Not Found) jquery.min.js:4 DELETE http://localhost/contributions/batches/batch/edit 404 (Not Found)

Here is button code这是按钮代码

<td class="text-center"><button type="button" class="btn btn-danger btn-sm btn-icon btn-destroy" 
                                                    data-batch-id="{{ $batch->id }}" 
                                                    data-id="{{ $contribution->id }}" 
                                                    data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
                                                    data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"
                                                ><i class="fa fa-times"></i></button>
                        </td>

Here is my script这是我的脚本

<script>

$(document).on('click', '.btn-destroy', function (e) {
    e.preventDefault();
    var batchId = $(this).data('batch-id');
    var id = $(this).data('id');
    var amount = $(this).data('amount');
    var contributor = $(this).data('contributor');
    swal({
            title: "Delete?",
            text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
            type: "error",
            showCancelButton: true,
            confirmButtonClass: 'btn-danger',
            confirmButtonText: "Delete",
            closeOnConfirm: false
        },
        function() {
            $.ajax({
                url: "{{ url('/contributions/contribution/destroy') }}",
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                type: "DELETE",
                data: {batch:batchId, contribution:id},
                success: function (data) {
                    console.log(data);
                    }               
            });
    });
});

oddly enough, refreshing the page after the error returns my session flash message from my controller's destroy function奇怪的是,错误后刷新页面从控制器的销毁函数返回我的会话闪存消息

*Note: I did add the DELETE verb to IIS, before this I was receiving: *注意:我确实在 IIS 中添加了 DELETE 动词,在此之前我收到了:

405 (METHOD NOT ALLOWED) 405(不允许的方法)

Any ideas?有任何想法吗?

Try this style of ajax 试试这种风格的ajax

$.ajax({
        url: "{{ url('/contributions/contribution/destroy') }}",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
       'data':{
         '_method':'delete',
          '_token':'{{ csrf_token() }}',
       },
       'method':'post'
});

After two days of reading and wrenching I have a working solution: 经过两天的阅读和训练,我有了一个可行的解决方案:

route: 路线:

Route::delete('/contributions/contribution/destroy', 'ContributionController@destroy');

link html: 链接html:

<a href="#" class="btn btn-danger btn-sm btn-icon btn-destroy" 
      data-id="{{ $contribution->id }}" 
      data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
      data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"><i class="fa fa-times"></i></a>

jquery/ajax: jQuery / ajax:

<script>

    $(document).on('click', '.btn-destroy', function (e) {
        e.preventDefault();
        var contributionId = $(this).data('id');
        var amount = $(this).data('amount');
        var contributor = $(this).data('contributor');
        swal({
                title: "Delete?",
                text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
                type: "error",
                showCancelButton: true,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: "Delete",
                closeOnConfirm: false
            },
            function() {
                $.ajax({
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    method: "DELETE",
                    url: "{{ url('/contributions/contribution/destroy') }}",
                    data: {contributionId:contributionId},
                    success: function (msg) {
                        if ( msg.status === 'success' ) {
                            swal("Deleted", msg.msg, "success");
                            setInterval(function() {
                                window.location.reload();
                            }, 3900);
                        }
                    },              
                    error: function(msg) {
                        swal("Error!", "Something went wrong.", "error");
                        console.log(msg.status);
                    }
                });
        });
    }); 

</script>

controller: 控制器:

public function destroy(Request $request)

{
    if ( $request->ajax() ) {

        Contribution::find($request->contributionId)->delete();

        return response(['msg' => 'Entry deleted', 'status' => 'success']);
    }
    return response(['msg' => 'Failed deleting the entry', 'status' => 'failed']);        
} 

Works perfectly! 完美的作品!

删除小牛

确认书

in my case I removed the error by running simple classic:在我的情况下,我通过运行简单的经典消除了错误:

php artisan route:clear

or you can launch that remotely.或者你可以远程启动它。 Create a route and a Controller and call it via browser link:创建路由和控制器并通过浏览器链接调用它:

Route::get('/b/{x}',  'for_stuff\BController@kukuku');

and put into the controller's function:并放入控制器的函数中:

Artisan::call('route:clear');

say:说:

https://mysite/b/r https://mysite/b/r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM