Laravel 5 访问 ajax Post 数据

Laravel 5 access to 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') 访问数据,但它总是空的。

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

您可以这样访问

$request['name of field'];

我认为您需要在控制器中接收数据 json:


    $request->json('field_of_interest')

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

In this question 提供了一个答案以使其起作用。

问题出在您的 formData 变量上。而不是:

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

应该是

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