如何将 JSON 返回数据作为参数传递给 URL 路由(laravel)

Posted

技术标签:

【中文标题】如何将 JSON 返回数据作为参数传递给 URL 路由(laravel)【英文标题】:how to pass JSON return data to a URL route as parameter(laravel) 【发布时间】:2019-01-26 08:08:18 【问题描述】:

我正在从事一个 Laravel 项目,并已成功实现 搜索功能,以使用带有 jquery 的 twitter typeahead 从数据库中搜索用户,但我卡住。我想将返回的 JSON 作为参数传递给路由 URL,以便在单击任何给定的建议结果时将其重定向到用户的个人资料页面。下面是我的代码。

suggestion: function(data) 
                    return '<a href="route('profile', ['username'=> 
'+ data.username +'])" class="list-group-item"> ' + data.username + 
'</a>'

使用此代码在单击时得到此结果 http://battlefield.test/profile/+%20data.username%20+ 相反,我想要 http://battlefield.test/profile/simon 要么 http://battlefield.test/profile/champion

下面是我要重定向到的路线

// Profile
Route::get('profile/username', [
'uses'=>'UserController@profile',
'as'=>'profile',
'middleware' => ['auth'],
]);

以下是与我的研究相关的链接,以防万一 https://scotch.io/tutorials/implementing-smart-search-with-laravel-and-typeahead-js

任何帮助将不胜感激。提前致谢。

【问题讨论】:

你可以使用 urldecode() 来解码这个问题。像这样 我希望你能明白。 迷路了。请详细说明@SoulCoder 如何在 laravel 中实现它 我们能看到返回的 json 吗?你还在控制器内部处理 json 数据吗? id: 1, username: "forever", firstname: "Simplest", lastname: "symon", gender: "Male" 这是我分配给数据的示例 JSON。我能够访问 data.username 当不在 url 内但在 url 内它不起作用这是我想要的@HasanTıngır 我明白了,我正试图逃离字符串 【参考方案1】:

我终于想出了一个解决方案。通常要从 Laravel 的视图中访问带有参数的路由,假设您有来自上述问题的以下路由

// Profile
Route::get('profile/username', [
'uses'=>'UserController@profile',
'as'=>'profile',
'middleware' => ['auth'],
]);

以下是通过href访问它的两种方式:

选项 1。

<a href="route('profile', ['username'=>here goes your parameter])"></a>

选项 2。

<a href="/profile/here goes your parameter"></a>

由于在我的情况下,我使用 JSON 数据来获取刀片模板“”中不容易访问的参数,因此第一个选项对我来说不太适用(如果有人知道为什么可以让我知道)但第二个做到了。这就是我如何将参数从 JSON 返回数据传递给 URL

'<a href="/posts/'+ data.username +'"></a>'

这里是一个示例返回数据,在这种情况下分配给数据

id: 1, username: "syk", first_name: "symon", last_name: "kibaru"

【讨论】:

【参考方案2】:

我尝试了很多尝试来弄清楚如何将数组传递到路由中,然后在控制器中接受它,所以有解决方案:

在表单动作中:

<form action="/purchase/ json_encode($items) " method="get">

在路线中:

Route::get('/purchase/items', [
        'uses' => Controllers\PurchaseController::class,
        'as' => '/purchase',
    ]);

在控制器中:

public function  __invoke($items)
    
        json_decode($items);
    

【讨论】:

以上是关于如何将 JSON 返回数据作为参数传递给 URL 路由(laravel)的主要内容,如果未能解决你的问题,请参考以下文章

Codeigniter - 如何将 JSON 作为参数传递给视图 [重复]

如何将 URL 中的数组作为参数传递给 Promise.all

如何将变量作为 cURL 数组中的 url 参数传递给 CURLOPT_URL

如何将json POST数据作为对象传递给Web API方法?

如何通过 URL 将参数传递给闪亮的应用程序

MVC - 将整个模型作为参数传递给 JavaScript 中的 Url.Action