Mat*_*one 9 javascript php laravel jquery-select2 laravel-5
我正在尝试使用Laravel和Select2进行动态下拉.有两个下降; 一个用于公司,即"company2",一个用于属于该公司的位置,即"location2".
对于我的生活,我无法弄清楚如何让"company2"下载一个事件来阅读那些公司的位置,如果它被改变了!我在这段代码的javascript部分做错了什么!(其他一切都有效)
路线
Route::controller('api', 'ApiController');
Run Code Online (Sandbox Code Playgroud)
控制器(ApiController)
public function getLocations($companyId)
{
return Location::where('company_id', $companyId)->lists('id', 'name');
}
Run Code Online (Sandbox Code Playgroud)
地址"api/locations/7"的示例输出
{"Yellowstone":"8"}
Run Code Online (Sandbox Code Playgroud)
查看(表格打开/关闭部分省略)
{!! Form::select('company_id', $companies, null, ['class' => 'company2 form-control']) !!}
{!! Form::select('location_id', $locations, null, ['class' => 'location2 form-control']) !!}
Run Code Online (Sandbox Code Playgroud)
查看(Javascript)
<script type="text/javascript">
$(document).ready(function() {
$(".company2").select2();
$(".location2").select2();
});
$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
url:"../api/locations/" + $company2.val(),
type:'GET',
success:function(data) {
var $location2 = $(".location2");
$location2.empty();
$.each(data, function(value, key) {
$location2.append($("<option></option>").attr("value", value).text(key));
});
$location2.select2();
}
});
}).trigger('change');
</script>
Run Code Online (Sandbox Code Playgroud)
视图在初始化时传递给活动公司列表,即
$companies = Company::lists('trading_name', 'id');
Run Code Online (Sandbox Code Playgroud)
用以下内容替换您的javascript,您可能需要调整一些.请务必仔细阅读评论.
var $company2 = $('.company2');
var $location2 = $(".location2");
$company2.select2().on('change', function() {
$.ajax({
url:"../api/locations/" + $company2.val(), // if you say $(this) here it will refer to the ajax call not $('.company2')
type:'GET',
success:function(data) {
$location2.empty();
$.each(data, function(value, key) {
$location2.append($("<option></option>").attr("value", value).text(key)); // name refers to the objects value when you do you ->lists('name', 'id') in laravel
});
$location2.select2(); //reload the list and select the first option
}
});
}).trigger('change');
Run Code Online (Sandbox Code Playgroud)
从控制器获取位置数据时更改以下内容
public function getLocations($companyId)
{
return Location::where('company_id', $companyId)->lists('name', 'id');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6316 次 |
| 最近记录: |