我正在尝试通过ajax将数据提交到数据库。无需使用ajax,提交文章页面可以正常工作。我添加console.log()只是为了查看是否发生了任何事情,但是却出现了此错误:
console.log()
POST http:// localhost / laravel-5 / public / articles / create 500(内部服务器错误)
我的代码有什么问题?是JavaScript还是控制器?
编辑:我正在这 laravel.log
laravel.log
C:\ xampp \ htdocs \ laravel-5 \ vendor \ laravel \ framework \ src \ Illuminate \ Foundation \ Http \ Middleware \ VerifyCsrfToken.php:53中的异常’Illuminate \ Session \ TokenMismatchException’
Route
Route::resource('articles', 'ArticlesController');
Controller
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); } }); });
View
<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>
});
当您通过POST向资源控制器发出请求时,它会自动调用存储方法:
Verb Path Action Route Name ---------------------------------- POST /articles store articles.store
因此,您只需要将ajax网址更改为:
$.ajax({ type: "POST", url: 'http://localhost/laravel-5/public/articles',
当您需要发送会话令牌时,可以添加一个全局元标记,例如您的网站:
<meta name="csrf-token" content="{{ csrf_token() }}">
然后,只需通过ajax的标头添加令牌:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
如果您使用的是Form::open()函数(LaravelCollective),它将添加一个隐藏的输入,其标记为name _token。因此,您可以删除元标记并像这样编辑ajax的标头:
Form::open()
_token
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('[name="_token"]').val() } });