【发布时间】:2015-09-18 19:14:43
【问题描述】:
为了解决这个问题,我已经在网上搜索了好几个小时。我对 AJAX 很陌生。因此,当我尝试将数据提交到控制器时,我在控制台中遇到了内部服务器 500 错误。我认为这是 CSRF 不匹配,但我已经尝试了所有我能想到的可以解决这个问题的方法。我在 layout.blade.php 中使用元标记方法进行 AJAX CSRF 提交。
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
</script>
我的评论代码如下所示。我将 $p->id 传递给路由,该路由将传递给控制器。
@if(Auth::check())
{!! Form::model($p, ['route' => ['new_comment.post', $p->id]]) !!}
<div class = "comment submit">
<textarea id = "comment_content" placeholder = "Your comment goes here!" name = "comment_content" class = "content_display comment"></textarea>
</div>
<div class = "action">
<li><a class = "comment_button new" href = "#"><i class = "fa fa-check"></i></a></li>
</div>
{!! Form::close() !!}
@else
<p><a href = "/login">Log in to post a comment</a></p>
@endif
我的 AJAX:
<script>
$('.comment_button.new').click(function(e) {
e.preventDefault();
var comment_content = $('#comment_content').val();
var data = 'comment_content'+comment_content;
var url = window.location.pathname;
$.ajax({
type : "POST",
url : url,
data : data,
success:function(data){
alert(data);
},
error:function(){
}
});
return false;
});
</script>
我的路线:
Route::post('/home/view/{id}', ['as' => 'new_comment.post', 'before' => 'csrf', 'uses' => 'ViewPost@new_comment']);
我的控制器:
class ViewPost extends Controller
{
public function show($id)
{
$posts = Posts::where('id', '=', $id)->get();
$comments = Comments::where('post_id', '=', $id)->get();
return view('view')->with('posts', $posts)->with('comments', $comments);
}
public function new_comment(Request $request, $id)
{
$comment_postID = $id;
$comment_data = $request->input('comment_content');
if($request->ajax()) {
$com = new Comment;
$com->post_id = $comment_postID;
$com->comment_content = $comment_data;
$com->save();
}
}
}
编辑
这是问题http://pastebin.com/tNcN5bLP的堆栈跟踪
已解决
正在使用“评论”调用我的“评论”模型。我通过在末尾添加一个 s 来修复它。哎呀!
还有,
我使用 AJAX 不正确地发布数据,因此我的控制器无法读取输入。这个片段来自我的 AJAX
var data = 'comment_content'+comment_content;
data : data,
应该是
data : {comment_content:comment_content},
谢谢!
【问题讨论】:
-
多考虑
var url = window.location.pathname;,写类似这样的url并测试url: window.location.pathname; + '/home/view/' + commentId -
@Pedrammarandi '/home/view/{{ $p->id }}' 提供与 window.location.pathname 相同的 url
标签: jquery ajax laravel internal-server-error