创建子类别选择框onChange [英] Create subcategory select box onChange
问题描述
我正在创建一个类别系统,用户可以从数据库中选择类别,然后在用户选择它之后,创建另一个具有该类别子类别的选择框.
I am creating a category system where users can select category from DB and after they select it creates another select box with subcategory of that category.
所以,我的问题是如何最好地做到这一点?
So, my question is how can I do it the best way?
顺便说一句,我正在使用Laravel Framework,第一类很简单
BTW I am using Laravel Framework and first category is simple
<select>
@foreach(Category::all() as $k)
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
@endforeach
</select>
但是,他们选择一个类别后该怎么办?进行AJAX调用以发送选择的类别的ID并返回子类别还是什么更好?
But what should I do after they pick a category? Is it better to do the AJAX call to send the ID of picked category and returns the subcategory or what?
我需要最好,最专业的方法来做到这一点.
I need the best and professional way to do this.
我的数据库中有
ID, name, parent
推荐答案
使用ajax
,在选择category
后发送ajax
请求,并执行此操作,您需要在
Use ajax
, after selecting the category
send the ajax
request and to do this you need to use change
event on your select
, for example:
// Assumed category is id of the select
$('#category').on('change', function(){
var id = $(this).val();
$.getJSON("subcategory/" + id , function(data){
// Assumed subcategory is id of another select
var subcat = $('#subcategory').empty();
$.each(data, function(k, v){
var option = $('<option/>', {id:k, value});
subcat.append(option);
});
});
});
在服务器端,创建如下路由(您可以使用控制器和Eloquent):
On the server side, create a route like this (You may use a controller and Eloquent):
Route('subcategory/{id}', function($id){
// Get the data from database according to the id
// Build an array as: id => value and then return
return Response::json($subcat);
});
这篇关于创建子类别选择框onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!