【问题标题】:Laravel API call through AJAX returns a lot of junkLaravel API 通过 AJAX 调用返回大量垃圾
【发布时间】:2021-06-15 15:37:03
【问题描述】:

我的 JS 代码(按钮处理程序):

$("#get-password").on("click", () => {
    $.get("https://psycho.bulash.ru/api/get.password").done(
        (data) => {
            console.log(data);
        }
    );
});

Laravel 路由(在 routes/api.php 中):

Route::group(['namespace' => 'App\Http\Controllers'], function () {
    Route::get('/get.password', 'HelperController@generatePassword');
});

控制器方法是:

public function generatePassword(int $length = 8): string
{
    return response()->json([
        'password' => Str::random($length)
    ], 200);
}

JS 代码在控制台中放入以下内容:

HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type:  application/json
Date:          Thu, 18 Mar 2021 08:23:20 GMT

{"password":"50Guz008"}<link rel='stylesheet' type='text/css' property='stylesheet' href='//psycho.bulash.ru/_debugbar/assets/stylesheets?v=1613988448&theme=auto'><script type='text/javascript' src='//psycho.bulash.ru/_debugbar/assets/javascript?v=1613988448'></script><script type="text/javascript">jQuery.noConflict(true);</script>
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), r...

几千字节的答案。

所以:

  1. 密码生成成功 - 我想要的
  2. 但 API 回答时附加了大量内容 - 为什么以及该怎么做?

【问题讨论】:

  • 你的代码中有dd()吗?
  • 在我只返回生成的密码的情况下,将 dd - junk 放在答案中也没关系 - return json_encode(['password' =&gt; Str::random($length])。我在回答中看到 - 是的,密码返回,但附加了垃圾
  • 那个垃圾是 laravel 调试栏附加的,由dd 生成的。它可能不在您共享的代码中,请检查您的服务提供商和中间件
  • 删除调试器会在返回数据后丢弃垃圾。也许您知道如何在 json 数据之前删除标头返回?

标签: json ajax laravel


【解决方案1】:

这是我对这个问题的实现!

在刀片中:

            $.ajax({
                url: url,
                headers: {'x-csrf-token': _token},
                method: 'GET',
                success: function (data) {
                    var officer = $('#officer');
                    if (data.length > 0) {
                        $.each(data, function (key, value) {
                            officer.append('<option value="' + value.id + '">' + value.name + '</option>')
                        })
                    } 
                }
            })

我的控制器:

public function getOfficers()
{
    $officers = User::where('project', '!=', null)->get();
    return $officers;
}

在你的情况下,我认为你只需要返回值而不使用响应!

public function generatePassword(int $length = 8): string
{
    return [
        'password' => Str::random($length)
    ];
}

【讨论】:

  • 谢谢。除了generatePassword 在这种情况下应该返回array,而不是string
  • 不客气,是的,您可以根据需要使用它!
【解决方案2】:

您很可能有中间件在您的响应后输出一些东西,检查它们

public function handle($request, Closure $next)
{
    return $next($request); 
    dd($something);//outputs after the response, remove this
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多