Laravel 5访问ajax Post Data

我正试图通过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'); 

控制器:

 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编码的主体。

在这个问题中 ,为此提供了答案。

你可以像这样访问

 $request['name of field']; 

我认为你需要以json的forms接收控制器中的数据:


     $请求 - > JSON( 'field_of_interest')

问题是你的formData变量。 代替:

 var formData = { form: $("#newCustomerForm").serialize() } 

它应该是

 var formData=$("#newCustomerForm").serialize();