获取405方法不允许例外

时间:2014-05-27 20:29:52

标签: jquery laravel

我有一个删除实体的jquery脚本(从github下载)。以下是脚本。

$(document).ready(function() {


var restful = {

    init: function(elem) {
        elem.on('click', function(e) {
            self=$(this);
            e.preventDefault();

            if(confirm('Are you sure you want to delete this record ? Note : The record will be deleted permanently from the database!')) {
                $.ajax({
                    headers: {
                        Accept : "text/plain; charset=utf-8",
                        "Content-Type": "text/plain; charset=utf-8"
                    },
                    url: self.attr('href'),
                    method: 'DELETE',
                    success: function(data) {
                        self.closest('li').remove();
                    },
                    error: function(data) {
                        alert("Error while deleting.");
                        console.log(data);
                    }
                });
            }
        })
    }
};

restful.init($('.rest-delete'));

});

我将其用作

{{link_to_route('download.delete','x', ['id' => $download->id], array('class'=> 'rest-delete label label-danger')) }}

相应的laravel路线如下

Route::delete('/deletedownload/{id}', array('uses' => 'DownloadsController@deletedownload', 'as'=>'download.delete'));

但是当我尝试按下X(删除按钮)时,我得到405方法不允许错误。错误如下

DELETE http://production:1234/deletedownload/42 405 (Method Not Allowed) . 

这在我的本地沙箱上工作正常。

任何帮助都将受到赞赏。

谢谢

1 个答案:

答案 0 :(得分:2)

您已使用method:DELETE代替在ajax来电

中使用以下内容
$.ajax({
    headers: {...},
    url: self.attr('href'),
    type:"post",
    data: { _method:"DELETE" },
    success: function(data) {...},
    error: function(data) {...}
});

Laravel会在_method中查找POST,如果找到该方法,则会使用DELETE请求。

更新nietonfirDELETE指出

您可以直接尝试$.ajax({ headers: {...}, url: self.attr('href'), type:"DELETE", success: function(data) {...}, error: function(data) {...} }); 方法(如果它不起作用,那么请尝试另一种方法),

{{1}}