2016-11-23 17 views
0

我在做功能,如果使用AJAX發送編輯表單,驗證,並將響應查看。但是,頁面加載新的URL,如localhost:8000/comment/id。並且該頁面顯示我想要的消息。我怎麼能得到這個迴應,以免重新加載?laravel ajax,如何發送值='put'成功的表單?

HTML

<form class="modify-form" method="post" action="{{ route('comment.update', $mypage->id) }}"> 
    <input type="hidden" name="_token" value="{{ csrf_token() }}"> 
    <input type="hidden" name="_method" value="put"> 
    <p class="comment-message">{{ $mypage->message }}</p> 
</form> 

路線

Route::match(['put', 'patch'], 'comment/{id}', ['as'=>'comment.update', 'uses'=>'[email protected]']); 

jQuery的

var $writeForm = $('form.visitor'); 
$writeForm.find('.write').click(function(e){ 

    var url = $writeForm.attr('action'); 

    e.preventDefault(); 
    $.ajax({ 
     url: url, 
     type: 'POST', 
     data: $writeForm.serialize(), 
     success: function(res){ 
      if (res.status) { 
       location.reload(); 
      } 
     }, 
     error: function(res){ 
       $writeForm.after('<div class="alert alert-danger" role="alert">'+res.responseJSON.errors+'</div>') 
       //console.log(res.responseJSON.errors); 
     } 

    }); 

}); 

控制器

public function update($id) { 

    $validator = validator::make($data = Input::all(), mypage::$edit); 

    if($validator->passes()) { 

     $mypage = mypage::findOrFail($id); 

     $message = Request::input('message'); 
     $mypage->update(['message' => $message]); 

     $mypage->save(); 

     $response = array(); 
     $response['status'] = true; 

     return response()->json($response); 

    } 

    if ($validator->fails()) { 

     $response = array(); 

     $response['status'] = false; 
     $response['errors'] = $validator->errors()->all(); 

     return response()->json($response, 400); 

    } 

} 
+0

我會reccommend使用Vue.js,我知道這可能不是你後的答案,但它是一個偉大的建議,因爲vue.js是輕便易用,與Laravel有很大的兼容性。 它可以讓你從輕鬆的後端拉動和後數據,並有很多的在您的處置comapred香草的Ajax方法的方法。 –

回答

0

您可以爲評論創建部分(小視圖)。

然後,當你創建/更新的評論,Laravel可以返回該視圖的評論,與jQuery追加到HTML。

可以造成局部的commment:(很簡單)

<p>{{$comment}}</p>

可以返回部分像任何觀點:

return view('partials.comment')->with('comment', $comment);

然後回到JS追加它像:

$("#comments-container").append(res);

+0

我可以請求一些例子嗎? – jungmyung

0

試試這個

Ajax:

type: $('input[name="_method"]').val(), 
data: $writeForm.serialize(), 
success: function(res){ 
    if (res.status == true) { 
     // Reload the current page, without using the cache 
     document.location.reload(true); 
    } 
}, 

Controller:

if ($validator->fails()) { 
    return response()->json([ 
     'status' => false, 
     'errors' => $validator->errors()->all() 
    ], 400); 

} 

if($validator->passes()) { 
    $mypage = mypage::findOrFail($id); 

    $message = Request::input('message'); 
    $mypage->update(['message' => $message]); 
    $mypage->save(); 

    return response()->json(['status' => true], 200); 
} 
+0

嗯,沒有工作 – jungmyung

+0

任何錯誤顯示到控制檯? –

+0

只是在新的URL上,{「status」:false,「errors」:[「該消息字段是必需的。」]}顯示爲 – jungmyung