Laravel 5 访问 ajax 发布数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35239599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:11:36  来源:igfitidea点击:

Laravel 5 access to ajax Post Data

phpjqueryajaxlaravellaravel-5.2

提问by DDL

I'm trying to receive data from a form through AJAX on Laravel 5.

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

JavaScript code:

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:

路线:

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);
}

In the network tab I can see how the parameters look like:

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

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"}

I also tried to access the data with $request->input('name of the field')but then it's always empty.

我也尝试访问数据,$request->input('name of the field')但它总是空的。

Does anybody have an idea what i'm doing wrong?

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

采纳答案by Davidonium

The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.

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

In this questionan answer is provided for this to work.

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

回答by svin

The problem is your formData variable. Instead of:

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

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

it should be

它应该是

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

回答by paranoid

You can access like this

你可以这样访问

$request['name of field'];

回答by René Juul Askj?r

i think you need to receive the data in the controller as json:

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

    $request->json('field_of_interest')