【发布时间】:2015-11-22 06:49:10
【问题描述】:
我正在尝试通过 ajax 向数据库提交数据。提交文章页面可以在没有 ajax 的情况下正常工作。我添加了console.log() 只是为了看看是否有任何事情发生,但我收到了这个错误:
POST http://localhost/laravel-5/public/articles/create 500(内部服务器错误)
我的代码有什么问题?是javascript还是控制器?
编辑:我在laravel.log得到这个
C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53 中的异常“Illuminate\Session\TokenMismatchException”:53
路线
Route::resource('articles', 'ArticlesController');
控制器
public function store(Requests\ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
$response = array(
'status' => 'success',
'msg' => 'Article has been posted.',
);
return \Response::json($response);
}
jQuery
$(document).ready(function() {
$('#frm').on('submit', function (e) {
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles/create',
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {
$("#ajaxResponse").append(data.msg);
console.log(data);
}
});
});
查看
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<h1>Write a New Article</h1>
<hr>
{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
<p>
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}
</p>
<p>
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}
</p>
<p>
{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</p>
<p>
{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
</p>
{!! Form::close() !!}
<h3 id="ajaxResponse"></h3>
@if($errors->any())
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
});
【问题讨论】:
-
检查你的 Laravel/服务器日志,了解 500 是由什么引起的。
-
这就是我得到的
exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53 -
@Halnex,你需要设置token,让我编辑答案
-
您的会话结束了吗?在此之前:Auth::user()->articles()->save($article);使用 if(Auth::check()) { //这里是代码} 检查会话是否处于活动状态
标签: php jquery ajax laravel laravel-5