[英]Sending ajax request in laravel 5
url = '{{route("ajaxSendmsg")}}';
console.log(url);
$.ajax({
url: url,
data : {comment_id:comment_id},
type: "POST",
dataType: "json",
success : function(response){
alert(response);
},
error : function(res){
console.log(res);
}
});
路线:
Route::post('/ajaxSend', ['as'=> 'ajaxSendmsg', 'uses'=>'PostsController@ajaxSend']);
控制器:
public function ajaxSend(){
if( Request::ajax() ){
return Response::json(['success' => 1]);
}
}
错误:VerifyCsrfToken.php 53行中的TokenMismatchException:
我正在尝试发送ajax请求,但是它不起作用。 :/
Laravel默认情况下对非读取HTTP请求(例如POST,PUT或PATCH)具有中间件,以防止跨站点请求伪造 。 在每个响应上,都会生成一个令牌,然后预期随后的请求将与该令牌一起发送。 如果令牌匹配,则一切正常,如果不匹配(或者请求完全不提供令牌),则可能是CSRF攻击。
有几种解决方法:
app/Http/Kernel.php
其注释掉来完全禁用中间件-显然不是最好的主意。 ``
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Support\Str;
class VerifyCsrfToken extends BaseVerifier
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Str::startsWith($request->getRequestUri(), 'some/open/route') {
return $next($request);
}
return parent::handle($request, $next);
}
}
_token
发送,要么在请求字符串中以_token
的形式发送,或者以名为X-CSRF-TOKEN
的HTTP标头发送。 您可以使用辅助函数csrf_token()
来获取它: ``
.ajax({
url: url,
data : {comment_id:comment_id, "_token":"{{ csrf_token() }}"},
type: "POST",
dataType: "json",
....
});
在laravel5中使用ajax请求和响应。 您应该像这样发送令牌。 :::::::::
ajax文件::
<input type="hidden" value="{{ csrf_token() }}" id="_token" name="_token" />
$.ajax({
type: 'POST',
url:'{{url("set-visitor")}}' ,
data: {id: '2', _token: $('#_token').val()},
dataType: 'html',
success: function(data){
var rep = JSON.parse(data);
console.log(data);
if(rep.code == 200)
{
console.log(rep);
}
else{
console.log('error');
}
}
});
和控制器文件::
public function set_visitor()
{
$id = request('id');
$_token = request('_token');
return Response::json($_token);
}
祝你好运:♥♥:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.