【问题标题】:Laravel 8: send Ajax (Fetch) data to Controller via POST methodLaravel 8:通过 POST 方法向 Controller 发送 Ajax (Fetch) 数据
【发布时间】:2023-02-25 04:43:26
【问题描述】:

我试图在控制器内部获取请求数据,但 Laravel 没有显示任何内容。在其他控制器中使用得到方法我可以轻松做到。

在这种情况下我不能使用页面重定向,所以 Ajax 是我唯一的选择。

我搜索了整个 stackoverflow,但找不到任何有用的东西。

我的代码:

web.php

Route::post('adiciona_credito', [AdicionaCreditoController::class, 'post_credito'])->name('adiciona_credito.post');

AdicionaCreditoController.php

<?php
    namespace App\Http\Controllers\MixVirtual;

    use App\Http\Controllers\Controller;
    use Exception;
    use Illuminate\Http\Request;

    class AdicionaCreditoController extends Controller {
        public function post_credito(Request $request): array {
            dd(request()->all()); // print the request
            try {
                // Saving data to the database.
                $retorno['msg']           = 'success';
            }
            catch (Exception $e) {
                $retorno['msg']    = $e->getMessage();
            }
            header('Content-type: application/json;charset=utf-8');
            return $retorno;
        }
    }

ajax.js

document.getElementById('form_adiciona_credito').addEventListener('submit', function(event) {
        event.preventDefault();
    
        let headers = new Headers();
        headers.append('X-CSRF-TOKEN', document.querySelector('[name="csrf-token"]').getAttribute('content'));

        let options = {
            method : 'POST',
            headers: headers,
            body   : JSON.stringify({
                credito      : document.getElementById('credito').value,
                justificativa: document.getElementById('justificativa').value
            })
        }

        fetch('./adiciona_credito', options).then(function(response) {
            if (!response.ok) {
                // Treating errors
            }
            response.json().then(function(return) {
                // AJAX callback
            });
        });
    }

HTML表格

<form id="form_adiciona_credito" method="post" action="{{route('adiciona_credito.post')}}">
                    @csrf
                    <div class="row">
                        <div class="col-12 my-1">
                            <input required type="number" class="form-control" id="credito" placeholder="Cr&eacute;dito para adicionar">
                        </div>
                        <div class="col-12 my-1">
                            <textarea required class="form-control" id="justificativa" placeholder="Justificativa"></textarea>
                        </div>
                        <div class="col-12 my-1">
                            <button class="btn btn-success float-end" id="btn_adiciona_credito">Add
                            </button>
                        </div>
                    </div>
                </form>

浏览器网络选项卡截图:

【问题讨论】:

  • 你在你的控制器中尝试过return response()-&gt;json($retorno);吗?
  • 我自己不使用 fetch() 方法,但如果您要发送 body: JSON.stringify(),那么如果您还将 contentType 标头设置为 application/json,那么 $request-&gt;all() 可能会起作用。或者试试application/x-www-form-urlencodedbody: {credito: ..., justificativa: ...}。在将 Laravel 用作 API 时,您不必使用 request()-&gt;getContent(),而是更多地处理您的请求,看看您是否可以让 $request-&gt;all()$request-&gt;input('credito') 工作。

标签: php ajax laravel forms request


【解决方案1】:

经过长时间的搜索,我发现我需要使用request()-&gt;getContent(); 来获取 POST 方法的主体参数。

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2012-01-20
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多