問題描述
我正在嘗試通過 ajax 向數據庫提交數據.提交文章頁面在沒有 ajax 的情況下工作正常.我添加了 console.log()
只是為了看看是否有任何事情發生,但我收到了這個錯誤:
I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log()
just to see if anything is going through, but instead I'm getting this error:
POST http://localhost/laravel-5/public/articles/create500(內部服務器錯誤)
POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)
我的代碼有什么問題?是 javascript 還是控制器?
What's wrong with my code? Is it the javascript or the controller?
我在 laravel.log
C:xampphtdocslaravel-5vendorlaravelframeworksrcIlluminateFoundationHttpMiddlewareVerifyCsrfToken.php:53 中的異常 'IlluminateSessionTokenMismatchException'
exception 'IlluminateSessionTokenMismatchException' in C:xampphtdocslaravel-5vendorlaravelframeworksrcIlluminateFoundationHttpMiddlewareVerifyCsrfToken.php:53
路線
Route::resource('articles', 'ArticlesController');
控制器
public function store(RequestsArticleRequest $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" >
<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="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
});
推薦答案
當你通過 POST 向資源控制器發出請求時,它會自動調用 store 方法:
When you make a request via POST to a resource controller, it automatically calls store method:
Verb Path Action Route Name
----------------------------------
POST /articles store articles.store
所以,你只需要把ajax url改成:
So, you just need to change ajax url to:
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles',
當您需要發送會話令牌時,您可以添加一個全局元標記,例如您的網站:
When you need to send the session token, you can add a global meta-tag like this is you website:
<meta name="csrf-token" content="{{ csrf_token() }}">
然后,只需通過ajax的標題添加令牌:
Then, just add the token via ajax's headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
如果您使用 Form::open()
函數 (LaravelCollective),它會添加一個隱藏輸入,其中包含名稱為 _token
的令牌作為值.因此,您可以刪除元標記并像這樣編輯 ajax 的標題:
If you are using Form::open()
function (LaravelCollective) it adds a hidden input with the token as value with the name _token
. So, you can remove the meta-tag and edit your ajax's headers like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
這篇關于Laravel 5:Ajax Post 500(內部服務器錯誤)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!