Laravel:通过 AJAX 向控制器发送数据,无需表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43214330/
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 15:43:07  来源:igfitidea点击:

Laravel: Send Data to Controller via AJAX Without Form

phpjqueryajaxlaravellaravel-5

提问by Ricky

I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically. Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.

我需要在单击按钮时通过 JS 将数据发送到 Laravel 控制器。我没有使用任何形式,因为数据是动态创建的。每次尝试发送数据时,都会收到内部服务器错误 (500),但无法在控制器或 laravel.log 文件中捕获该异常。

Here's what i'm doing:

这是我在做什么:

Route:

路线:

Route::post('section/saveContactItems', 'SectionController@saveContactItems');

Controller:

控制器:

public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }

JS:

JS:

$('button').on("click", function (evt) {

    evt.preventDefault();

    var items = [];
    var id = $("#id").val();
    var languageID = $("#languageID").val();
    var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };

    $.ajax({
        url: "/section/saveContactItems",
        type: "POST",
        data: data,
        cache: false,
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (response)
        {
            console.log(response);
        }
    });
});

What am i doing wrong? How can i accomplish this?

我究竟做错了什么?我怎样才能做到这一点?

UPDATE: Thanks to @ShaktiPhartiyal's answer(and @Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following @Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:

更新:感谢@ShaktiPhartiyal 的回答(以及@Sanchit 的帮助),我能够解决我的问题。万一其他人遇到类似问题,在遵循@Shakti 的回答后,我无法访问控制器中的数据。因此,我必须在将数据发送到服务器之前对其进行字符串化:

data: JSON.stringify(data),

采纳答案by Shakti Phartiyal

You do not need to use

你不需要使用

public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }

You have to do the following:

您必须执行以下操作:

public function saveContactItems()
{
    $id = Input::get('id');
    $type = Input::get('type');
    $items = Input::get('items');
    $languageID = Input::get('languageID');
}

and yes as @Sanchit Gupta suggested you need to send the CSRF token with the request:

是的,因为@Sanchit Gupta 建议您需要随请求发送 CSRF 令牌:

Methods to send CSRF token in AJAX:

在 AJAX 中发送 CSRF 令牌的方法:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

If you use this approach you need to set a meta tag like so:

如果您使用这种方法,则需要像这样设置元标记:

<meta name="csrf-token" content="{{csrf_token()}}">

or

或者

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }

UPDATE

更新

as @Sanchit Gupta pointed out use the Input facade like so:

正如@Sanchit Gupta 指出的那样使用 Input 外观:

use Input;