问题
I'm developing an application with Laravel 5.1 and I have a problem when sending ajax petition I have the next code:
View for Create:
{!!Form::open()!!}
<div class="form-group">
{!!Form::label('genero','Genre:')!!}
{!!Form::text('genre',null,['id'=> 'genre','class'=>'form-control'])!!}
</div>
{!!link_to('#', $title = 'Create', $attributes = ['id'=> 'create','class'=>'btn btn-primary'], $secure = null)!!}
{!!Form::close()!!}
Ajax Petition:
$("#create").click(function(){
var genre = $("#genre").val();
var route = "http://localhost:8000/genre";
$.ajax({
url: route,
type: 'POST',
dataType: 'json'
data: {genre : genre}
});
})
In my Routes:
Route::resource('genre','GenreController');
But when send the petition I have the next error:
POST http://localhost:8000/genre 500 (Internal Server Error)
Thanks.
回答1:
In default template , add meta tag
<meta name="_token" content="{!! csrf_token() !!}"/>
Then add script code :
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
Then you can use ajax call...as normal
回答2:
My solution was the next code:
$("#registro").click(function(){
var data = $("#genre").val();
var route = "http://localhost:8000/genre";
var token = document.getElementById('token').value
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: {data : data}
});
});
来源:https://stackoverflow.com/questions/31416965/send-form-for-create-with-ajax-and-laravel-5-1