[英]Ajax Callback to append a select dropdown html to table?
I am trying to append some html using jQuery using below code. 我试图使用下面的代码使用jQuery附加一些HTML。 This whole thing i am just trying to select an option using ajax response data and building a select dropdown.
我只是想使用ajax响应数据选择一个选项并构建一个select下拉列表。 But
sOut
variable scope not able to persist appended html inside callback function looping. 但是
sOut
变量作用域无法将附加的html持久保存在回调函数循环中。 Is there any work around to achieve what i am doing? 有什么工作可以实现我的目的吗?
getVendor(aData[2], function (response) {
var obj = jQuery.parseJSON(response);
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
var industries_select = '<tr><td>Industry:</td><td><select class="form-control m-bot15">';
getIndustries(function (response) {
var industries = jQuery.parseJSON(response);
for (var l = 0; l < industries.length; l++) {
if (industries[l].id == obj.industry) {
industries_select += '<option value="' + industries[l].id + '" selected="selected">' + industries[l].name + '</option>'
} else {
industries_select += '<option value="' + industries[l].id + '">' + industries[l].name + '</option>'
}
}
});
industries_select += '</select></td></tr>';
sOut += industries_select;
sOut += '</table>';
});
That's the expected behavior of async request. 这是异步请求的预期行为。 you should be doing something like this
你应该做这样的事情
getVendor(aData[2], function (response) {
var obj = jQuery.parseJSON(response);
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
var industries_select = '<tr><td>Industry:</td><td><select class="form-control m-bot15">';
getIndustries(function (response) {
var industries = jQuery.parseJSON(response);
for (var l = 0; l < industries.length; l++) {
if (industries[l].id == obj.industry) {
industries_select += '<option value="' + industries[l].id + '" selected="selected">' + industries[l].name + '</option>'
} else {
industries_select += '<option value="' + industries[l].id + '">' + industries[l].name + '</option>'
}
}
industries_select += '</select></td></tr>';
sOut += industries_select;
sOut += '</table>';
});
});
Because, the callback of getIndustries
will be called later point in time, and when the time you access industries_select
outside the function, it's undefined. 因为,
getIndustries
的回调将在稍后的时间点被调用,并且当您在函数外部访问industries_select
的时间时,它是未定义的。
If, for example, you're building the HTML dynamically then you may try appending the sOut variable to a Div tag inside your function scope, for example: 例如,如果您要动态构建HTML,则可以尝试将sOut变量附加到函数范围内的Div标签中,例如:
HTML: HTML:
<div id="dynamic"></div>
JQuery: jQuery的:
$("#dynamic").append(sOut);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.