簡體   English   中英

Laravel和jQuery DataTable刪除行

[英]Laravel and jquery datatable delete row

我正在使用laravel 5.2,Jquery 1.10和MYSQL 5.7。

我在laravel中將RESTful服務用於消息模型。

我試圖在Jquery數據表中呈現消息列表,並在每行上提供一個刪除按鈕,當按下該按鈕時應觸發MessageController.php上的destroy方法,刪除該行然后重新加載消息索引頁以顯示更新的數據表。

最初已正確生成數據表,但刪除按鈕不會觸發控制器上的刪除方法。 我假設用於生成刪除按鈕的ajax代碼一定是錯誤的。

在此先感謝您的幫助。

我的數據表ajax腳本是-

  $(document).ready( function () {
    $('#message_table').DataTable({

        "searchable": false,
        "ajax": {
            "url": "/api/message",
            "type": "POST",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        },
        "columns": [
            { "data": "id"},
            { "data": "subject",
                "render": function(data,type,row,meta) {
                    return '<a href="/message/'+row.id+'">'+data+'</a>';
                }
            },
            { "data": "created_at",
                "render": function ( data, type, full, meta ) {
                    // instantiate a moment object and hand it the string date
                    var d = moment(data);
                    var month = d.month() +1 < 10 ? "0" + (d.month() +1) : d.month() +1;
                    var day = d.date()  < 10 ? "0" + (d.date()): d.date();
                    return month + "/" + day + "/" + d.year();
                }
            },
            {"defaultContent": "null", "render": function(data,type,row,meta) {
                return '<button action="' + $(location).attr('protocol') + $(location).attr('host') + '/message/'+row.id+ '"' + 'name="_method"' + 'method="post"' +'type="submit"' + 'value="Delete"'+'>'+ 'Delete</button>';
            }
            }
        ]
    });
} );

從上一個函數為刪除按鈕生成的HTML是-

<button action="http:localhost:8000/message/6" name="_method" method="post" type="submit" value="Delete">Delete</button>

消息控制器刪除方法-

   public function destroy($id)
{
    Message::destroy($id);

    return Redirect::route('message.index');
}

如果您使用的是laravel的restful控制器,則destroy方法是通過delete http方法。 因此,最好的選擇是創建一個小的表單,例如:

<form action="http:localhost:8000/message/6" method="post">
    <input type="hidden" name="_method" value="delete">
    <button type="submit">Delete</button>
</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM