gpt4 book ai didi

php - Laravel 5 访问ajax Post数据

转载 作者:行者123 更新时间:2023-12-01 04:42:17 28 4
gpt4 key购买 nike

我正在尝试通过 Laravel 5 上的 AJAX 从表单接收数据。

JavaScript 代码:

event.preventDefault();     // Disable normal behaviour of the element (Form)

var formData = {
form: $("#newCustomerForm").serialize() // Transmit all input data of the form serialized
}

console.log(formData); // Log to the console the Input data

$.ajax({
type: 'post', // POST Request
url: 'save', // Url of the Route (in this case user/save not only save)
data: formData, // Serialized Data
dataType: 'json', // Data Type of the Transmit
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');

if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler

// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});

路线:

Route::post ('user/save', 'CustomerController@createNewCustomer');

Controller :

public function createNewCustomer (Request $request)
{
$inputArray = $request->all();

print_r ($inputArray['form']);

// Set JSON Response array (status = success | error)
$response = array ('status' => 'success',
'msg' => 'Setting created successfully',);
// Return JSON Response

return response ()->json ($response);
}

在网络选项卡中,我可以看到参数的样子:

radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}

我还尝试使用 $request->input('name of the field') 访问数据,但它始终为空。

有人知道我做错了什么吗?

最佳答案

问题是您正在调用 $("#newCustomerForm").serialize(),并且此方法以 url 编码的参数而不是 json 编码的正文序列化表单。

In this question为此提供了答案。

关于php - Laravel 5 访问ajax Post数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35239599/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com