我有这个功能
function actInfo(fund) {
var acct = $('.account');
$.ajax({
url: "account.php",
type: 'get',
dataType: 'json',
data: {fund: fund}
}).done(function (response) {
var len = response.length;
acct.empty();
for (var i = 0; i < len; i++) {
var acctNum = response[i]['ID'];
var acctName = response[i]['NAME'];
acct.append("<option value='" + acctNum + "'>" + acctNum + ' -- ' + acctName + "</option>");
}
acct.prepend("<option value=''>- Select An Account -</option>").val('');
}).fail(function (jqXHR, textStatus, error) {
console.log("actInfo: " + error);
});
}
我在另一个ajax调用中调用此函数,因为我需要发送从服务器获取的函数变量。在我用来调用actInfo(基金)的同一个ajax调用中,我也试图选择一个值。这是主要的ajax调用。
function getPoInfo(trnum) {
$.ajax({
url: "edit.php",
data: {trnum: trnum},
type: "GET",
cache: false,
dataType: "json"
}).done(function (poInfo) {
$('#fund').val(poInfo[0]['TRANFUND']);
actInfo(poInfo[0]['TRANFUND']);
$('#account1').val(poInfo[0]['TRANACCOUNT'].trim());
}).fail(function (jqXHR, textStatus, error) {
console.log("getPoInfo(tran_num): " + error);
});
}
actInfo(fund)
功能正常。它构建我的下拉菜单。但我不知道如何选择一个值。我假设我在下载加载之前尝试选择一个值。我不理解回调或承诺,我尝试.bind
并试图追加.done
和.load
,但我无法选择值。如何确定下拉菜单何时完成加载,然后选择一个值?
答案 0 :(得分:1)
由于actInfo()
方法包含异步操作(基本上<select>
元素仅在您收到并解析返回的JSON响应后构建)。因此,你想要的是:
var deferred = new $.Deferred()
return deferred.promise()
。应根据内部AJAX请求的结果解析新的延迟对象(deferred.resolve()
)或拒绝(deferred.reject()
)。
如果我们考虑所有这些要点,您的代码可以很容易地重构如下(我添加了评论,我添加了建议的更改):
function actInfo(fund) {
var acct = $('.account');
// Create new deferred object
var deferred = new $.Deferred();
// Perform AJAX call as usual
$.ajax({
// Truncated for brevity
// ...
}).done(function (response) {
var len = response.length;
acct.empty();
for (var i = 0; i < len; i++) {
var acctNum = response[i]['ID'];
var acctName = response[i]['NAME'];
acct.append("<option value='" + acctNum + "'>" + acctNum + ' -- ' + acctName + "</option>");
}
acct.prepend("<option value=''>- Select An Account -</option>").val('');
// Now that the DOM has been built, we can resolve the promise and return it!
deferred.resolve();
}).fail(function (jqXHR, textStatus, error) {
console.log("actInfo: " + error);
// If we encounter an error, we pass it on!
deferred.reject(error);
});
// Return immutable promise
return deferred.promise();
}
然后,在getPoInfo()
方法中,只需检查actInfo()
返回的承诺的解决方案:
function getPoInfo(trnum) {
$.ajax({
// Truncated for brevity
// ...
}).done(function (poInfo) {
$('#fund').val(poInfo[0]['TRANFUND']);
// actInfo returns a promise!
var actInfoPromise = actInfo(poInfo[0]['TRANFUND']);
// Wait for the promise to resolve using $.when
$.when(actInfoPromise)
.then(function() {
// If successful, we select the correct <option>
$('#account1').val(poInfo[0]['TRANACCOUNT'].trim());
}, function(error) {
// If failed, we log the error message that has been passed on
console.log(error);
});
}).fail(function (jqXHR, textStatus, error) {
console.log("getPoInfo(tran_num): " + error);
});
}