如何向Laravel 5.0框架发送Ajax请求? [英] How to send an Ajax request to Laravel 5.0 framework?
问题描述
我整个上午都在尝试解决问题,但似乎无法在网上找到任何可行的方法.
I've tried to fix this all morning and I can't seem to find any working method online.
我正在尝试对我的Laravel控制器执行一个简单的ajax请求,并获取它发送的数据.我已将其简化到最大程度,但仍然出现错误500,数据为未定义".
I'm trying to do a simple ajax request to my Laravel controller and get the data it sends. I've simplified it to the maximum and I still get ERROR 500 with data "undefined".
似乎在线上的每个示例都是关于Laravel 4.0的,我不确定它们是否更改了某些内容,但似乎都没有用.我还尝试将路由更改为"any",并且该路由可用于直接访问,但不适用于ajax请求.
It seems that every examples onlines are about Laravel 4.0, I'm not sure if they changed something or not but none seem to work. I also tried changing the route to "any" and it works on the direct access but not with the ajax request.
谢谢.
控制器:
<?php namespace App\Http\Controllers;
use Session, DB, Request;
class AjaxController extends Controller {
public function question()
{
print_r("Made It");
die();
}
}
路线:
Route::post('/ajax/question', 'AjaxController@question');
JavaScript:
Javascript :
$.ajax({
url: "/ajax/question",
method: 'POST',
data: { 'answered': '1' },
processData: false,
contentType: false,
cache: false,
success: function(data) {
console.log(data);
console.log("success");
},
error: function(data) {
console.log(data);
console.log("error");
}
});
console.log(data)提供以下内容:
console.log(data) gives the following :
readyState
4
responseText
""
status
500
statusText
"Internal Server Error"
abort
function(e)
always
function()
complete
function()
done
function()
error
function()
fail
function()
getAllResponseHeaders
function()
getResponseHeader
function(e)
overrideMimeType
function(e)
pipe
function()
progress
function()
promise
function(e)
setRequestHeader
function(e, t)
state
function()
statusCode
function(e)
success
function()
then
function()
如果我将请求更改为GET,则它可以正常工作. (将路线设置为任意)
EDIT : If I change the request to GET it works properly. (Set route to any)
推荐答案
If you look in your browser console at the response, chances are you're hitting the CSRF middleware. You need to post _token
with the current value for the user's csrf_token()
.
我们将其包含在页面布局中,以便通过标头(Laravel理解)将其自动添加到所有AJAX请求中:
We include this in our page layouts in order to automatically add it to all AJAX requests via a header (which Laravel understands):
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!};,
}
});
});
</script>
请参见 https://github.com/laravel/framework/blob/8687d42c6674e47efc093b5092ea217b62ba293a/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php#L55 了解其工作原理的详细信息.
See https://github.com/laravel/framework/blob/8687d42c6674e47efc093b5092ea217b62ba293a/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php#L55 for details on how that works.
这篇关于如何向Laravel 5.0框架发送Ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!