php Laravel 5:Ajax Post 500(内部服务器错误)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32256969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5: Ajax Post 500 (Internal Server Error)
提问by Halnex
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:
我正在尝试通过ajax向数据库提交数据。提交文章页面在没有 ajax 的情况下工作正常。我添加console.log()
只是为了看看是否有任何事情发生,但我收到了这个错误:
POST http://localhost/laravel-5/public/articles/create500 (Internal Server Error)
POST http://localhost/laravel-5/public/articles/create500(内部服务器错误)
What's wrong with my code? Is it the javascript or the controller?
我的代码有什么问题?它是javascript还是控制器?
EDIT: I'm getting this in laravel.log
编辑:我得到这个 laravel.log
exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
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
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>
});
});
回答by manix
When you make a request via POST to a resource controller, it automatically calls store method:
当您通过 POST 向资源控制器发出请求时,它会自动调用 store 方法:
Verb Path Action Route Name
----------------------------------
POST /articles store articles.store
So, you just need to change ajax url to:
因此,您只需要将 ajax url 更改为:
$.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() }}">
Then, just add the token via ajax's headers:
然后,只需通过 ajax 的标头添加令牌:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
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:
如果您使用的是Form::open()
函数 (LaravelCollective),它会添加一个隐藏输入,其标记为名称为 的值_token
。因此,您可以删除元标记并像这样编辑 ajax 的标题:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
回答by ceejayoz
That's what I got exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Htt??p\Middleware\VerifyCsrfToken.php:53
这就是我在 C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Htt??p\Middleware\VerifyCsrfToken.php:53 中得到的异常 'Illuminate\Session\TokenMismatchException'
You're hitting Laravel's CSRF protection.
您遇到了 Laravel 的 CSRF 保护。
http://laravel.com/docs/5.1/routing#csrf-protection
http://laravel.com/docs/5.1/routing#csrf-protection
You need to pass the hidden _token
field's value. This can be done automatically on all jQuery-initiated AJAX requests by doing this in your application's JS:
您需要传递隐藏_token
字段的值。通过在应用程序的 JS 中执行此操作,可以在所有 jQuery 启动的 AJAX 请求上自动完成此操作:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').value()
}
});
Or, you can manually fetch and pass the value of the _token
hidden field in each of your AJAX calls.
或者,您可以_token
在每个 AJAX 调用中手动获取并传递隐藏字段的值。
回答by Jumaycito
I like to share this code to help someone to need ajax post and get with laravel
我喜欢分享此代码以帮助需要 ajax 帖子并使用 laravel 的人
<<<<<<<<
POST
<<<<
<<look after @extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
@extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contrase?a." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login4')}}',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
alert(data);
console.log(data);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::post('login4', function()
{
return 'Success! POST Ajax in laravel 5';
})->name('login4');
------------------0----------------------
------------------0----------------------
<<<<
Get
<<look after @extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
@extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contrase?a." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login2')}}',
type: "get",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
obj = JSON.stringify(data, null, " ");
var datito = JSON.parse(obj);
console.log(datito.response);
alert(datito.response);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::get('login2', 'WebController@login2')->name('login2');
-------------0----------------------
-------------0----------------------
<<<----<<Http\Controllers\WebController.php<<<<-----------<<<
public function login2(Request $datos) {
if ($datos->isMethod('get')) {
return response()->json(['response' => 'This is get method']);
}
return response()->json(['response' => 'This is post method']);
}
-------------0----------------------
-------------0----------------------
回答by Danish Jamshed
You can add your URLs to the VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification:
您可以将您的 URL 添加到 VerifyCsrfToken.php 中间件。URL 将从 CSRF 验证中排除:
protected $except = [ "your url", "your url/abc" ];
回答by Shubh
Well if you are looking for the sure shot answer ,here it is : This error particularly occurs if you are missing csrf_token() in your code Here is what I did,
好吧,如果您正在寻找可靠的答案,那么这里是:如果您的代码中缺少 csrf_token(),则尤其会发生此错误这就是我所做的,
<h6>ITEMS ORDERED:<a href="#" id="{{$post->identifier}}" onclick="getcart(this.id)">CLICK HERE</a></h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Now With Ajax
现在使用阿贾克斯
<script type="text/javascript">
function getcart(val) {
var alpha=val;
var token=document.getElementById('token').value;
$.ajax({
type:'post',
url:'/private/getcart',
data:{'alpha':alpha,'_token': token},//this _token should be as it is
success:function (result) {
alert(result);
}
});
}
</script>
In my laravel controller
在我的 Laravel 控制器中
public function getcart(Request $req)
{
return response ("its");
}