3

我是 Laravel 框架的新手,但我真的很喜欢它。我最大的问题是我一直在寻找如何使用资源控制器删除单个记录。

控制器方法:

public function destroy($id) {
    $department = Department::find($id);
    $department->delete();
}

删除我试过的链接:

<a class="btn btn-xs btn-danger" data-method="delete" href="{{ URL::to('department/' . $department->id) }}"><i class="icon-remove"></i></a>

Javascript:

<script type="text/javascript">
$(function(){
    $('[data-method]').append(function(){
        return "\n" +
        "form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" + 
        "<input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n" +
        "</form>\n"
    })
    .removeAttr('href')
    .attr('style', 'cursor: pointer;')
    .attr('onclick', '$(this).find("form").submit();');
});

现在,当我单击删除链接时,它不起作用。关于我做错了什么的任何想法,我一直在寻找这么久。

4

3 回答 3

1

Use $.post() to trigger your click instead of that form creation/submission:

$(document).on("click", "[data-method]", function(e) {
    e.preventDefault();

    $.post($(this).attr('href'), {/* the id goes here */});
});

Apply the cursor style via CSS. I must admit that I'm not sure if laravel expects a HTTP DELETE instead of a post. And I think you missed to submit the id of the department you want to delete.

[edit] As laravel expects a HTTP DELETE you can't use the $.post() shorthand, but $.ajax() instead:

$(document).on("click", "[data-method]", function(e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr('href'),
        type: "DELETE",
        data: {/* the id goes here */},
        success: function(data, textStatus, jqXHR) {
             console.log("success");
        }
    });
});
于 2013-10-03T20:02:10.820 回答
1

The destroy() will be called in DELETE request and not in POST request.

So try ,

<a class="btn btn-xs btn-danger" onclick="deleteDepartment($department->id)" href="javascript:void(0)"><i class="icon-remove"></i></a>

And in javascript,

function deleteDepartment(id) {
  $.ajax({
    url: 'department/'+id,
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
  });
}
于 2013-10-03T20:02:54.043 回答
0

感谢您的回答,它的工作原理就像我只是在创建表单时忘记了开头 < 即我被错误地写了:

"form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" + 

代替:

"<form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" + 
于 2013-10-04T06:22:06.800 回答