控制器不会 Return 查看 Laravel

Controller Won't Return View Laravel

我正在使用 Laravel 8 制作网络应用程序。

除以下功能外,我的所有控制器功能均正常工作:

  public function show(Request $id)
    {
        return response()->view('locations.show', compact('id'));
    }

我已确定可以访问此控制器,但没有任何反应,页面也没有重定向到我指定的视图。

web.php:

Route::get('/getlocation', [App\Http\Controllers\LocationController::class, 'show']);

当我尝试手动访问路线时,页面显示视图。

如果您需要更多信息,请告诉我。谢谢。

编辑:根据要求添加一些代码。

javascript

$("#getLocation" + spot.ID).click(function () {
    $.get(getLocation, spot.ID);
});
var getLocation = '{{action('App\Http\Controllers\LocationController@show')}}';

我尝试过的事情

编辑 2:

我做了一些修改,但页面仍然没有重定向。

javascript:

$("#getLocation" + spot.ID).click(function () {
    $.post("/getlocation", JSON.stringify(spot));
});

web.php:

Route::post('/getlocation', [App\Http\Controllers\LocationController::class, 'show']);

Route::get("/showspot", function (Request $location) {
    return view('locations.show', compact('location'));
})->name("showLocation");

位置控制器:

public function show(Request $location)
{
    return redirect()->route('showLocation', json_decode($location));
}

我在点击按钮后收到关于参数丢失的错误,所以我不得不在我的 javascript 文件和控制器中分别使用 JSON.stringify()json_decode()。现在单击按钮时我没有收到任何错误,但页面仍未重定向到请求的视图。

我确实在我的 cmd window 运行 php artisan serve 中注意到,当我单击按钮时,请求正在发生:[Sun Dec 5 16:32:09 2021] 127.0.0.1:64795 Accepted [Sun Dec 5 16:32:10 2021] 127.0.0.1:64795 Closing

但同样,不是重定向。

编辑 3

更多详情: 我在这里试图完成的是将对象从我的 javascript 代码发送到 locations.show 视图并重定向到该视图。显示的 javascript 代码位于获取 JSON 对象并循环遍历它的获取请求中,显示对象中的每个对象。

$.each(jsonSpots, function (key, spot) {
    if (spot.NAME.search(inputExpression) != -1 || spot.TYPE.search(inputExpression) != -1) {
        results.push(spot);
        $('h3').html("Total: " + resultsCount);

        $('#result').append(
            '<li id="spot' + spot.ID + '" class="spot list-group-item">' +
            '<strong>Name: </strong>' + spot.NAME + '<br/>' +
            '<strong>Address: </strong>' + spot.ADDRESS + '<br/>' +
            '<button class="btn btn-info" id="getLocation' + spot.ID + '" >More Details</button>' +
            '<br>'
        );

        $("#getLocation" + spot.ID).click(function () {
            $.post(getLocation, spot, function (data) {
                if (data.success) { // data.success is a boolean
                    window.location.href = data.url;
                }
            });
        });

        if (authenticated) {
            $("#spot" + spot.ID).append(
                '<button type="button" class="btn btn-dark" id="addSpot' + spot.ID + '" >Add To Map</button>'
            );
            $("#addSpot" + spot.ID).click(function () {
                $.post(addSpot, spot);
                drawPins("all");
            });
        }

        $('#result').append('</li>');
    }
});

感谢@Daedalus 的回复,我对为什么我最初试图完成的事情没有奏效有了更多的理解,并且由于能够实现我的目标,对他的建议进行了一些改动:

javascript:

备注:

$("#getLocation" + spot.ID).click(function () {
    $.post(getLocation, spot, function (data) { 
)
        if (data.success) {
            window.location.href = data.url;
        }
    });
});

web.php:

备注:

Route::post('/getlocation', [App\Http\Controllers\LocationController::class, 'show']);

Route::get("/showspot", function (Request $location) {
    return view('locations.show', compact('location'));
})->name("showLocation");

控制器:

备注:

public function show(Request $location)
{
    return [
        'success' => true,
        'url' => route('showLocation',
            [
                'NAME' => $location->NAME,
                'LONGITUDE'=> $location->LONGITUDE,
                'LATITUDE' => $location->LATITUDE,
                'ADDRESS' => $location->ADDRESS,
                'TYPE' => $location->TYPE,
                'ID' => $location->ID
            ])
        ];
}

现在,所有参数都显示在 URL 中,我想绕过它。

我意识到这不是完成我需要的好方法,所以任何额外的建议都非常有必要。

这里有几种方法可以实现您的目标。但是,重要的是要了解为什么您最初的尝试没有奏效。

$("#getLocation" + spot.ID).click(function () {
    $.post("/getlocation", JSON.stringify(spot));
});

此代码段仅向 /getlocation 发送 POST 请求。它不对响应数据做任何事情。通常,如果您希望当前活动的页面响应或响应该请求,您需要添加一个额外的匿名函数作为该方法的最后一个参数,如下所示:

$("#getLocation" + spot.ID).click(function () {
    $.post("/getlocation", JSON.stringify(spot), function (data) {
        // Do something with the data variable
    });
});

data,在这种情况下,如 the documentation for $.post 所定义,是一种智能猜测的数据类型,具体取决于服务器发回的内容。它可以是 JSON、xml 或其他内容,例如纯字符串。对于您的代码,数据可能是来自服务器端代码作为响应发送的重定向的 html(视图的)字符串。

Ajax 遵循重定向,但它不会更改当前活动页面,除非您将其编码为。

现在,就是说,我执行此操作的方法要简单得多。由于您已经希望有一个重定向,因此使用 ajax 可能没有任何实际意义。您可以只使用一个表单,并让该表单的 POST 请求的处理程序 return 重定向到您想要结束的页面。

但是,假设您的代码比那更复杂,并且无法使用简单的方法,我会这样做:

Javascript:

$("#getLocation" + spot.ID).click(function () {
    $.post("/getlocation/" + spot.ID, function (data) {
        if (data.success) { // data.success is a boolean
            window.location.href = data.url;
        }
    });
});

根据您的代码和写作,我将假设 Location 是一个模型。通过将 $location 转换为 Request,您不太可能得到您认为的那样;请求 class is defined here。无论如何,基于该假设,您应该 use 该模型和类型提示:

路线:

use App\Models\Location; // Assuming this is where your model is.

Route::post('/getlocation/{location}', [App\Http\Controllers\LocationController::class, 'show']);

Route::get("/showspot/{location}", function (Location $location) {
    return view('locations.show', compact('location'));
})->name("showLocation");

控制器:

public function show(Location $location)
{
    return [
        'success' => true,
        'url' => route('showLocation', ['id' => $location->id]);
    ];
}

success 当然可以根据您的实际操作进行更改。 Laravel 能够从路由处理程序中获取 returned 数组并将其转换为 JSON,因此无需重做该部分。路由模型绑定解释 more in-depth here.

为了响应您的第三次编辑,可以通过使用 Javascript 创建一个表单元素,向该元素添加输入,然后将带有 POST 请求的表单提交给所需的操作 url。示例如下:

控制器:

public function show(Request $location)
{
    return [
        'success' => true,
        'url' => route('showLocation'),
        'location' => [
            'NAME' => $location->NAME,
            'LONGITUDE'=> $location->LONGITUDE,
            'LATITUDE' => $location->LATITUDE,
            'ADDRESS' => $location->ADDRESS,
            'TYPE' => $location->TYPE,
            'ID' => $location->ID
        ]
    ];
}

Javascript:

$("#getLocation" + spot.ID).click(function () {
    $.post("/getlocation/" + spot.ID, function (data) {
        if (data.success) { // data.success is a boolean
            let formEl = document.createElement('form');
            formEl.method = 'POST';
            formEl.action = data.url;
            
            Object.keys(data.location).forEach(function (key) {
                let inputEl = document.createElement('input');
                inputEl.type = 'hidden';
                inputEl.name = key;
                inputEl.value = data.location[key];
                formEl.appendChild(inputEl);
            });
            
            document.body.appendChild(formEl);
            formEl.submit();
        }
    });
});

您重定向到的页面上的其他代码可以保持不变,前提是您当然访问 Request class 并将名称、经度等分配给视图。

这个想法来自 here,所以我建议您尽可能给这个答案投赞成票。