在使用Dependent下拉菜单时,通常会在数据库中存储关联的ID,而不是显示的名称。这样做有几个基础概念和优势:
以下是一个简单的Laravel和JavaScript示例,展示如何实现Dependent下拉菜单并在数据库中存储ID。
// routes/web.php
Route::get('/dependent-dropdown', [DependentDropdownController::class, 'index']);
Route::post('/dependent-dropdown', [DependentDropdownController::class, 'store']);
// app/Http/Controllers/DependentDropdownController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Country;
use App\Models\State;
class DependentDropdownController extends Controller
{
public function index()
{
$countries = Country::all();
return view('dependent-dropdown', compact('countries'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'country_id' => 'required',
'state_id' => 'required',
]);
// 存储数据到数据库
$data = [
'country_id' => $validatedData['country_id'],
'state_id' => $validatedData['state_id'],
];
// 保存数据到数据库
// ...
return redirect()->back()->with('success', 'Data saved successfully!');
}
}
<!-- resources/views/dependent-dropdown.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dependent Dropdown</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form action="/dependent-dropdown" method="POST">
@csrf
<label for="country">Country:</label>
<select id="country" name="country_id">
<option value="">Select Country</option>
@foreach ($countries as $country)
<option value="{{ $country->id }}">{{ $country->name }}</option>
@endforeach
</select>
<label for="state">State:</label>
<select id="state" name="state_id">
<option value="">Select State</option>
</select>
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#country').change(function() {
var countryId = $(this).val();
$.ajax({
url: '/get-states',
method: 'GET',
data: { country_id: countryId },
success: function(response) {
var options = '';
$.each(response.states, function(key, state) {
options += '<option value="' + state.id + '">' + state.name + '</option>';
});
$('#state').html(options);
}
});
});
});
</script>
</body>
</html>
通过以上步骤和示例代码,可以实现一个基本的Dependent下拉菜单,并在数据库中存储关联的ID。
领取专属 10元无门槛券
手把手带您无忧上云