
本文介绍如何通过 jquery + ajax 实现 select2 下拉框的动态选项加载——当用户切换“库存来源”时,自动获取并渲染对应库存中的商品列表,前后端协同完成数据联动与响应式更新。
本文介绍如何通过 jquery + ajax 实现 select2 下拉框的动态选项加载——当用户切换“库存来源”时,自动获取并渲染对应库存中的商品列表,前后端协同完成数据联动与响应式更新。
在构建表单交互时,常需实现「级联选择」效果:例如先选库存(Inventory),再根据所选库存动态加载其可用商品(Products)到另一个支持搜索的 Select2 组件中。这不仅提升用户体验,也确保数据一致性。以下为完整、可落地的实现方案。
✅ 前端:监听变更 + 发起请求 + 初始化 Select2
首先确保页面中已引入 jQuery 和 Select2(含 CSS/JS):
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"><script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
HTML 中定义两个下拉框(注意第二个需有 id="products" 以便 JS 操作):
<select class="form-control" id="from-location" name="from-location"><option value="">-- 请选择库存 --</option> <option value="1">Inventory 1</option> <option value="2">Inventory 2</option> <option value="3">Inventory 3</option></select><select id="products" name="products[]" multiple style="width: 100%;"></select>
使用 jQuery 监听 #from-location 的 change 事件,并向后端发起带参数的 AJAX 请求:
$(document).ready(function() {
$('#from-location').on('change', function() {
const inventoryId = $(this).val();
// 清空并销毁原有 Select2 实例(避免重复初始化)
$('#products').select2('destroy').empty();
if (!inventoryId) return; // 未选择时不请求
$.ajax({
type: 'GET',
url: '/inventory-products',
data: { inventory: inventoryId },
dataType: 'json',
success: function(response) {
$('#products').select2({
data: response,
placeholder: '请选择商品...',
allowClear: true,
width: '100%'
});
},
error: function(xhr) {
console.error('加载商品失败:', xhr.responseJSON?.message || '未知错误');
alert('无法获取该库存的商品,请稍后重试。');
}
});
});
});
⚠️ 注意事项:
- 每次切换前调用 .select2('destroy') 避免重复绑定或样式错乱;
- 使用 multiple 属性支持多选(如需单选可移除并设 data: response[0]);
- dataType: 'json' 必须与后端返回类型严格一致,否则 response 可能为字符串而非数组。
✅ 后端:Laravel 路由 + 模型关系 + JSON 响应
修正路由(注意 URL 一致性,前端请求 /inventory-products,路由需匹配):
// routes/web.php
Route::get('/inventory-products', [LogicForms::class, 'inventory_products']);
确保模型已正确定义多对多关系(通过中间表 product_stocks):
// app/Models/Inventory.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
protected $table = 'inventories';
public function products()
{
return $this->belongsToMany(Product::class, 'product_stocks', 'inventory_id', 'product_id');
}
}
// app/Models/Product.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
}控制器方法接收 inventory 参数,查询对应商品,并格式化为 Select2 所需的 {id: ..., text: ...} 数组:
// app/Http/Controllers/LogicForms.php
<?php namespace App\Http\Controllers;
use App\Models\Inventory;
use Illuminate\Http\Request;
class LogicForms extends Controller
{
public function inventory_products(Request $request)
{
$inventoryId = $request->input('inventory');
// 防御性检查
if (!$inventoryId || !is_numeric($inventoryId)) {
return response()->json([], 400);
}
$inventory = Inventory::find($inventoryId);
if (!$inventory) {
return response()->json([], 404);
}
$products = $inventory->products()->select('id', 'name')->get();
// 格式化为 Select2 兼容结构
$data = $products->map(function ($p) {
return ['id' => $p->id, 'text' => $p->name];
});
return response()->json($data);
}
}✅ 此处使用 ->select('id', 'name') 提升性能;->map() 替代手动 foreach 更简洁安全;状态码(400/404)便于前端做精细化错误处理。
✅ 补充建议与优化方向
- 缓存优化:若商品列表变动不频繁,可在控制器中加入 Laravel 缓存(如 Cache::remember("inventory_{$inventoryId}_products", 3600, ...));
- 搜索增强:Select2 默认支持远程搜索(ajax mode),如需服务端过滤,可扩展接口接收 q 参数并添加 WHERE name LIKE %q%;
- 加载状态提示:在 AJAX 请求前后添加 .prop('disabled', true) 或 loading spinner,提升反馈感;
- SEO 与降级:对 JS 禁用场景,可预渲染默认选项或提供
通过以上步骤,即可实现库存与商品间的动态联动下拉,兼顾健壮性、可维护性与用户体验。










