Javascript jQuery文档就绪调用序列
我对jQuery有以下问题。我使用以下代码:Javascript jQuery文档就绪调用序列,javascript,jquery,Javascript,Jquery,我对jQuery有以下问题。我使用以下代码: function populate_select_from_json(select, json_url) { select.empty(); $.getJSON(json_url, function(data) { $.each(data, function(key, value) { $("<option></option>") .att
function populate_select_from_json(select, json_url) {
select.empty();
$.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo(select);
});
});
select.children(":first").attr("selected", true);
}
$(document).ready(function() {
var value_type = $("#value_type");
populate_select_from_json(value_type, SOME_URL);
var unit = $("#unit");
populate_select_from_json(unit, ANOTHER_URL + value_type.val());
});
我想:
加载文档
从关联数据库获取一些JSON数据
将数据放入值\类型项中
获取value_type select的值,并再次查询数据库以填充另一个select项。
问题是,当我调用value_type.val时,它总是输出null,即使正确填充了value_type。我做错了什么?我想这样的事情可能更适合我 沿着这些未经测试的路线:
var populate_select_from_json = function($select, json_url) {
$select.empty();
return $.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo($select);
});
$select.children(":first").attr("selected", true);
});
};
jax是异步的。调用value_type.val时,该字段尚未填充。我建议使用延迟对象来链接Ajax调用:。正如我所想!看起来这片土地还没有人居住。浏览器是否在另一个线程中调用了我的方法,因此它有点像是从.ready回调中派生出来的呢?我想为了检索数据,一些后台进程已经启动,但是JS中没有线程。
$(document).ready(function() {
var $value_type = $("#value_type");
var $unit = $("#unit");
populate_select_from_json($value_type, SOME_URL).done(function(){
populate_select_from_json($unit, ANOTHER_URL + $value_type.val());
});
});