我遇到了一个问题,我无法通过AJAX将变量传递给Laravel Controller。这是我的代码:
AJAX函数提交订单:
function submitOrder() {
console.log(JSON.stringify(order.positions));
console.log('SENDING ORDER ',order.positions, ' to the database');
event.preventDefault();
// var id = this.id;
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'Content-Type':'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
//FIXME No response
dataType: 'json',
type: "post",
url: '/orders/api/store',
data: {
_method: 'post',
_token: CSRF_TOKEN,
order: JSON.stringify(order.positions)
},
success: function( response ) {
console.log(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
routes.php
Route::post('/orders/api/store', 'OrdersController@apiStore');
和控制器功能:
public function apiStore(Request $request) {
$response = [
'request' => $request->order,
'responseText' => 'works',
'status' => '200'
];
return response()->json($response);
}
我得到的答复:
SENDING ORDER [{…}]0:
{product_id: 3, name: "Мороженое фрукты", price: "45.00", quantity: "1"}
to the database // Sending this array
response {request: null, responseText: "works", status: "200"} //This is the response from Laravel
如您所见,请求变量为null,但必须为$request->order
值,由AJAX发送。
答案 0 :(得分:2)
我建立了一个快速的原型,这对我来说是一个可行的例子:
// web.php
Route::post('/test', 'HomeController@test');
// HomeCrontroller.php
class HomeController extends Controller
{
// ...
public function test()
{
$response = [
'request' => request()->data,
'responseText' => 'works',
'status' => '200'
];
return response()->json($response);
}
// ...
}
// some js
axios
.post("/test", {
data: {
value: "key"
}
})
.then(res => console.log(res));
// outcome of console.log(res)
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data:
request: {value: "key"}
responseText: "works"
status: "200"
// ...
如果这不适用于您-检查您的版本。
答案 1 :(得分:0)
经过2天的尝试,我终于找到了解决方法:创建数据变量(对象),设置是否包含所需数据的if字段,并在传递给后端时将其JSON化。
function submitOrder() {
console.log(JSON.stringify(order.positions));
console.log('SENDING ORDER ',order.positions, ' to the database');
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var data = {};
data.order = order.positions;
data._method = 'POST';
data._token = CSRF_TOKEN;
$.ajax({
type: "POST",
url: '/orders/api/store/',
data: JSON.stringify(data),
success: function( response ) {
console.log(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}