簡體   English   中英

Ajax無法在Laravel 5.5上運行

[英]Ajax not working on Laravel 5.5

我剛剛開始學習Laravel 5.5,以探索一個“高級”框架。 我曾經使用Codeigniter並喜歡它。 現在,我正在實現一個小的CRUD功能,並且可以正常工作。 現在,我嘗試使用Jquery AJAX,因此不必刷新。 我之前在以前的codeigniter項目中使用過Jquery AJax。 現在,當我使用Laravel嘗試時,它不起作用。 我檢查了許多參考資料,但不確定為什么它沒有成功。 我正在嘗試將其實現為Delete函數,如果可以正常運行,我敢保證其余的工作都可以完成。

問題:

  1. 當我嘗試刪除它時,它會重定向到“ json”視圖。 我認為那是因為return response ()->json ($post); 但是是的,該項目將刪除。
  2. 當我檢查開發人員控制台時,沒有發出AJAX請求。 我認為AJAX不會被調用,它直接進入表單的動作。

我希望它成為

  1. AJAX有效。 無需刷新頁面。

控制者

    public function destroy($id)
{
    $post = Post::find($id);
    if (auth()->user()->id !== $post->user_id){
      return redirect ('/posts')->with('error', 'Unauthorized page');
    }
    $post->delete();
    return response ()->json ($post);
}

路線

Route::resource('posts','PostsController');

視圖

{!!Form::open(['action'=>['PostsController@destroy', $post->id], 'method'=>'POST', 'class'=>''])!!}
                            {{Form::hidden('_method', 'DELETE')}}
                            {{Form::button('Delete', ['type' => 'submit', 'class' => 'btn btn-danger delete','id' => 'delete', 'data-id' => $post->id ] )}}
                          {!!Form::close()!!}

JS

  <script type="text/javascript">
$(document).ready(function(){
  $(".delete").on('click',function(event){
    var id = $(this).attr('data-id');
    alert(id);
    $.ajax({
      url: "posts/"+id,
      type: "DELETE",
      success: function(){
        alert("DELETED");
      }
    });
  });
});
  </script>

非常感謝你的朋友!

問題是您要在觸發REST調用之前提交表單,因此您的rest調用永遠不會停止,但是頁面會重新加載,因為表單已提交,然后顯示了從控制器返回的json。

在刀片視圖中刪除Form 然后像這樣更新ajax:

$(document).ready(function() {
   var id = {!! $post->id !!};
   $.ajax({
      url: "posts/"+id,
      type: "DELETE",
      contentType: 'application/json',
      success: function(data) {
         console.log(data);
         alert("DELETED");
      }
   });
});

暫無
暫無

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

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