You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel与JS:如何在GET请求中传递两个参数

解决方法:无需POST,用GET传递可选参数

当然可以不用转成POST请求!咱们一步步来搞定这个问题:

1. 先更新路由定义

你的控制器方法新增了可选的$quantity参数,所以得先调整路由,让它支持这个可选参数——在路由里用{quantity?}的格式(问号表示该参数可选):

// 原路由
// Route::get('admin/toys/collections/products/{collectionName}', 'Admin\ToysController@products');

// 更新后的路由(推荐加上路由名称,方便后续生成URL)
Route::get('admin/toys/collections/products/{collectionName}/{quantity?}', 'Admin\ToysController@products')->name('admin.toys.products');

2. 修改AJAX请求的写法

有两种可靠的方式构造GET请求的URL,都能完美适配你的需求:

方式一:用Laravel的route()函数生成URL(最省心)

这个方法会自动处理可选参数:如果$quantity是null,生成的URL会自动忽略它;如果有值,就自动拼到路径里。

<?php 
$collectionName = "testing"; 
$quantity = "55"; 
?>
<script>
$.ajax({
    type: 'get',
    url: "{{ route('admin.toys.products', [$collectionName, $quantity]) }}",
    success: function(response) {
        // 这里处理接口返回的数据
        console.log(response);
    },
    error: function(xhr) {
        // 处理错误情况
        console.error(xhr.responseText);
    }
});
</script>

方式二:手动拼接URL(适合灵活场景)

如果你不想给路由命名,也可以手动拼接URL,注意处理$quantity为空的情况:

<?php 
$collectionName = "testing"; 
$quantity = "55"; 
?>
<script>
// 先构造基础URL
let requestUrl = "{{ url('admin/toys/collections/products') }}/" + "{{ $collectionName }}";
// 如果quantity有值,就拼到URL后面
if ("{{ $quantity }}" !== "") {
    requestUrl += "/" + "{{ $quantity }}";
}

$.ajax({
    type: 'get',
    url: requestUrl,
    success: function(response) {
        console.log(response);
    }
});
</script>

额外选项:用查询字符串传递参数(无需改路由)

如果你不想调整路由,也可以把$quantity作为查询参数传递(比如admin/toys/collections/products/testing?quantity=55),这时候需要修改控制器的参数获取逻辑:

public function products($collectionName) {
    // 从请求中获取quantity,默认值为null
    $quantity = request()->get('quantity', null);
    // 后续业务逻辑...
}

对应的AJAX写法可以用data属性传递参数:

<?php 
$collectionName = "testing"; 
$quantity = "55"; 
?>
<script>
$.ajax({
    type: 'get',
    url: "{{ url('admin/toys/collections/products') }}/" + "{{ $collectionName }}",
    data: {
        quantity: "{{ $quantity }}"
    },
    success: function(response) {
        console.log(response);
    }
});
</script>

内容的提问来源于stack exchange,提问作者burtonLowel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:22:41