【问题标题】:laravel modal delete confirmation does not go to destroy routelaravel modal 删除确认不会去破坏路由
【发布时间】:2014-10-29 11:52:25
【问题描述】:

当我在注释掉模态对话框脚本的情况下运行此代码时,我看到我的控制器消息弹出。当我尝试使用脚本时,会出现模式弹出窗口,但单击确定或取消什么也不做。我怀疑这与“attr('action')”有关,但我找不到它的文档,也不知道如何让它路由到控制器。我尝试将“操作”更改为“销毁”和“删除”,但没有成功。

          <td> {{Form::open(array('method'=>'DELETE', 'route' => array('users.destroy', $user->id)))}} 
               {{Form::submit('Delete', array('class'=>'btn btn-danger'))}}
               {{Form::close()}}
          </td>

脚本

<script>
$(document).ready(function(){
   $('.btn-danger').submit(function(e){
     e.preventDefault();
     url = $(this).parent().attr('action');
     BootstrapDialog.confirm('Are you sure you want to delete?', function(result){
       if(result) {
         $.ajax(url);
       }
     });
   });
});
</script>

控制器

public function destroy($id)
{
    print_r($id);
//       User::find($id)->delete();
//      return View::make('hello');
        Response::json(['message'=>'Delete was successful']);

}

在我的路线中

Route::resource('users', 'UserController');

运行它显示的 php artisan 路由

URI: DELETE users/{users} | Name: users.destroy | Action: UserController@destroy

如下所示更改 jquery 行将继续到控制器消息,但现在缺少模式确认。

url = $(this).parent().attr('action');
BootstrapDialog.confirm('Are you sure you want to delete?', function(result){
if(result) {
   $.ajax({url:url, 
           type:"DELETE",
           success: function(data, textStatus, jqXHR) {
                    alert(data.message + textStatus + jqXHR.responseText);},
           error: function(jqXHR, textStatus, errorThrown) {
                    alert('Failure: ' + textStatus + ". Error: " + errorThrown);}
           });

【问题讨论】:

    标签: jquery laravel bootstrap-modal


    【解决方案1】:

    您的 Routes.php 文件是什么样的?

    确保您拥有Route::delete('users/{id}', ['uses' =&gt; 'UsersController@destroy', 'as'=&gt;'users.destroy']);

    其次,如果您使用 ajax,您需要确保为 ajax 定义 'type' 选项,以确保将其设置为 type: 'DELETE' 否则 jQuery.ajax() 将默认使用 'POST'。见这里:http://api.jquery.com/jquery.ajax/

    编辑: 只是指出“action”属性只是将表单指向它应该发布到的 URL,它没有定义它应该使用的 METHOD(POST、GET、PUT、DELETE)。

    【讨论】:

    • 谢谢!我更改了 jquery 行以将类型设置为 DELETE 和要删除的操作,它现在可以工作了。
    • 其实我很快就和我谈过了,插入该行打破了模式确认但继续显示控制器弹出消息
    • 不确定该 jquery 更改是否有效。试试$.ajax({url: url, type :"DELETE"}); 还检查取消确认时实际返回的结果。
    • 我使用了一些警告框来查看确认框的结果为“result=true”。但是“url = undefined”。我一直无法弄清楚如何正确形成它。
    • 顺便说一句,我在你的 JS 中看到了这个问题。你有 $(this).parent().attr() 其中 $(this) 是指表单,如果你删除 .parent() 它应该工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2017-06-12
    • 2021-06-18
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多