[英]Sending data from javascript to Laravel Controller
I've got a problem with sending data from javascript to my controller. 将数据从javascript发送到控制器时出现问题。 There is my Ajax :
有我的Ajax :
var point = JSON.stringify(points);
function onBtnClick() {
$.ajaxSetup({
header:{
'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
}
});
$.post('http://localhost/updateC', {
data: point,
dataType: 'json',
contentType:'application/json',
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
}
Routes: 路线:
Route::get('/home', 'HomeController@index')->name('home');
Route::resource('/races','RacesController');
Route::post('updateC', 'RacesController@Points');
And there is my RacesController: 还有我的RacesController:
public function Points(Request $request) {
$test = $request->input('data');
return "$test";
}
And the error is saying that has been blocked by CORS-polices. 错误是说这已被CORS政策阻止。
go the middleware folder, the verifycsrftoken file, 转到中间件文件夹,verifycsrftoken文件,
app/Http/Middleware/VerifyCsrfToken.php
and add this url to the except array 并将此网址添加到除外数组
protected $except = [
....
http://localhost/updateC
];
to handle exceptions to your ajax post requests, then you can then use the 处理您的ajax发布请求的异常,那么您可以使用
Barryvdh Laravel Cors package to get rid of cors issue, Barryvdh Laravel Cors软件包摆脱了cors问题,
if you are using laravel 5.6, you dont need any CORs package for that, 如果您使用的是laravel 5.6,则不需要任何CORs软件包,
just create a CORs Middleware 只需创建一个CORs中间件
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next) {
$allowedOrigins = ['http://oursite.com', '*.myost.net','*','www.aminu.*'];
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (in_array($origin, $allowedOrigins)) {
return $next($request)
->header('Access-Control-Allow-Origin', $origin)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, cache-control,postman-token, token')
->header('Access-Control-Allow-Credentials',' true');
}
return $next($request);
}
}
and add middleware to the kernel.php file 并将中间件添加到kernel.php文件
protected $middleware = [
......
\App\Http\Middleware\Cors::class, //added here
];
You have to add csrf token in your data
property of ajax post like this: 您必须像这样在ajax post的
data
属性中添加csrf令牌 :
data: {
"_token": "{{ csrf_token() }}",
"point": point
}
app/Http/Middleware/VerifyCsrfToken.php
and add this route to the except array 并将此路由添加到除外数组
protected $except = [
'updateC'
];
Ajax code Ajax代码
var abc = 'hello world';
$.ajax({
type: "GET",
url: 'http://your url',
data : { abc : abc }
success: function (data) {
// write your code
},
error: function (data) {
// write your code
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.