【问题标题】:How to avoid or prevent 500 Internal Server Error after executing AJAX script?执行 AJAX 脚本后如何避免或防止 500 Internal Server Error?
【发布时间】:2017-05-24 06:41:27
【问题描述】:

我在我的项目中为 Modal CRUD 修改了 AJAX 脚本,因为我在解码一些提供的示例时遇到了麻烦。但是我在我的 AJAX 删除脚本中遇到了这个问题,控制台说:

POST http://localhost:8000/deleteItem 500(内部服务器错误) 发送@app.js:10552 ajax@app.js:10159 (匿名)@ dept_pagination:944 dispatch @ app.js:6192 elemData.handle@app.js:6000

我注意到“deleteItem”不是我要重定向到的网址。在我的 Ajax 脚本中,我指出了“deleteItem_dept”,但在执行后,它运行良好,但控制台抛出此错误,并且 url 更改为“deleteItem”,这是另一个页面视图的 url。下面是我的 Ajax 脚本

<script type="text/javascript">
  function dept_delete(id)
    {
      $('#footer_action_button_dept').text(" Yes");
      $('#footer_action_button_dept').removeClass('glyphicon-check');
      $('#footer_action_button_dept').addClass('glyphicon-trash');
      $('.actionBtndept').removeClass('btn-success');
      $('.actionBtndept').addClass('btn-info');
      $('.actionBtndept').addClass('delete');
      $('.id').text($(this).data('id'));
      $('#deleteContentdept').show();
      $('.form-horizontal').show();
      $('#delModal').modal('show');

    $('.modal-footer').on('click','#deldept', function(){
          if (id == '')
          {
            alert('No department selected.')
          }
          else
          {
            $.ajax({
              url: "/deleteItem_dept",
              type: "post",
              data: {
                '_token': $('input[name=_token]').val(),
                'id': id
              },
                success: function(data) {
                  document.getElementById(id).remove();
                  id = undefined; //reset ID to undefined
                  $('.form-horizontal').show();
                }
            });
          }
      });
      $('.modal-footer').on('click','#candept', function(){
        id = undefined; //reset ID to undefined
        $('.form-horizontal').show();
      });
    }
</script>

控制器逻辑

public function deleteItem_dept(Request $request)
{
    $data = $request->id;
    DeptOffice::where('id', $data)->delete();
    return response()->json();
}

【问题讨论】:

  • 可以分享删除路由和控制器吗?通常,您在 url 中传递要删除的项目 id。
  • 公共函数 deleteItem_dept(Request $request) { $data = $request->id; DeptOffice::where('id',$data)->delete();返回响应()->json(); }
  • 你能申请我的代码吗?
  • @ResnefImmatong 请按照该帖子中的说明进行操作,您将使其正常工作

标签: jquery ajax laravel


【解决方案1】:

它应该在您的控制器中处理。先检查对象是否存在

public function deleteItem_dept(Request $request) { 
    $data = $request->id; 
    if ($record = DeptOffice::where('id',$data)->first()) {
        $record->delete()
    } 
    return response()->json(); 
} 

【讨论】:

  • @ResnefImmatong 更新答案先检查数据
  • 还是一样,它也会抛出警报消息但控制台仍然有错误结果。
猜你喜欢
  • 2011-05-08
  • 2015-09-15
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多