javascript 使用 jQuery 和 Laravel 框架发布请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28386534/
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
Post request with jQuery and Laravel framework
提问by Vladimir
I need to receive data from jQuery post request, think there is some error with routs or controller, here is my post request javascript code:
我需要从 jQuery 发布请求接收数据,认为路由或控制器存在一些错误,这是我的发布请求 javascript 代码:
$.post('http://localhost:8000/ajax',
{
task: "comment_insert",
userID: _userID,
comment: _comment,
name: _name,
userName: _userName
}
).error(
function(data)
{
alert("Error: "+ data);
}
)
.success(
function( data )
{
comment_insert(jQuery.parseJSON( data ));
console.log("RESPOND TEXT:" + data);
}
);
}
Also here is my routes for Laravel framework:
另外这里是我的 Laravel 框架路线:
Route::post('ajax', 'AjaxController@index');
Controller:
控制器:
class AjaxController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('ajax.ajax');
}
}
my ajax.php script is into /resource/views/ajax/ajax.php Also if I put script into /public/ajax/ajax.php all works fine....I use Laravel 5... Please help
我的 ajax.php 脚本进入 /resource/views/ajax/ajax.php 另外,如果我将脚本放入 /public/ajax/ajax.php 一切正常....我使用 Laravel 5...请帮忙
EDIT:
编辑:
I found what is problem but don't know how to solve.
我发现了什么问题,但不知道如何解决。
When I disable csrf protection from: kernel.php code work anyone know how to make code work with csrf protection enabled?
当我从以下位置禁用 csrf 保护时: kernel.php code work 有谁知道如何使代码在启用 csrf 保护的情况下工作?
回答by cgross
UPDATE:The problem is that the new CSRF-protection does not work with ajax-requests. Here is what you could do:
更新:问题是新的 CSRF 保护不适用于 ajax 请求。您可以这样做:
In your master template add a new meta tag with the current token like this
在您的主模板中添加一个带有当前令牌的新元标记,如下所示
<meta name="csrf-token" content="{{ Session::token() }}">
Then when sending your ajax call you add the token like this:
然后在发送您的 ajax 调用时,您添加这样的令牌:
$.post('http://localhost:8000/ajax',
{
'_token': $('meta[name=csrf-token]').attr('content'),
task: 'comment_insert',
userID: _userID,
comment: _comment,
name: _name,
userName: _userName
})
.error(
...
)
.success(
...
);
}
回答by Robert Ni?o
Is a simple code with javascript to send methods GET,POST,PUT,DELETE
是一个简单的代码,用 javascript 发送方法 GET,POST,PUT,DELETE
declare header: <meta name="csrf-token" content="{{ Session::token() }}">
声明标题: <meta name="csrf-token" content="{{ Session::token() }}">
function addCarrito(Urldir,paramt)
{
$(function(){
$.post(Urldir,{ _token: $('meta[name=csrf-token]').attr('content'), _method : 'PUT', data : }, function(response){
if(response != '')
{
console.log('good');
}
});
});
}