我不确定我是否正确地提出了这个问题。我正在动态构建网格(行,列)中的数据库记录的显示。一些单元格使用表单对象,我使用AJAX来帮助构建它们(select中的选项存储在db表中)。所以我的代码看起来像这样(AJAX调用的返回是完整的...设置:
...
//写单元格html if(d == 1){ userdata + =“”+ thisitemarray [1] +“
”; 如果(d == 2){,则为else
//make ajax call to get departments
$.ajax({
type: "POST",
url: "lib/getDropDowns.php",
data: "thistable=departments&selecteditem=" + thisitemarray[1] + "&classnames=userdept userdatainput",
success: function(data){
userdata += "<p class=\"datacell department\">" + data + "</p>";
}
});
} else if (d == 3) {
userdata += "<p class=\"datacell bucket\"><input type=\"text\" value=\"" + thisitemarray[1] + "\" class=\"userbucket userdatainput\" dbid=\"" + dbid + "\"></p>";
} else if (d == 4) {
userdata += "<p class=\"datacell pubcode\"><input type=\"text\" value=\"" + thisitemarray[1] + "\" class=\"userpubcode userdatainput\" dbid=\"" + dbid + "\"></p>";
} else if (d == 5) {
userdata += "<p class=\"datacell area\"><input type=\"text\" value=\"" + thisitemarray[1] + "\" class=\"userarea userdatainput\" dbid=\"" + dbid + "\"></p>";
} else if (d == 6) {
userdata += "<p class=\"datacell hours\"><input type=\"text\" value=\"" + thisitemarray[1] + "\" class=\"userhours userdatainput\" dbid=\"" + dbid + "\"></p>";
} else if (d == 7) {
userdata += "<p class=\"datacell description\"><textarea class=\"userdesc\" dbid=\"" + dbid + "\">" + thisitemarray[1] + "</textarea></p>";
}//end d check 2
问题是这行代码:
success: function(data){
userdata += "<p class=\"datacell department\">" + data + "</p>";
}
未显示在我的页面上。我假设因为userdata被视为函数中的局部变量。如何将从AJAX传递的数据拉出到我的脚本中以便我可以使用它?
答案 0 :(得分:1)
在循环之前添加一个计数器:
var counter = 0;
稍后将其用作ID生成器:
if (d === 1) {
userdata += "" + thisitemarray[1];
} else if (d === 2) {
var id = 'datacell_department_' + counter;
counter++;
userdata += "<p class=\"datacell department\" id=\""+id+"\"></p>";
//make ajax call to get departments
$.ajax({
type: "POST",
url: "lib/getDropDowns.php",
data: "thistable=departments&selecteditem=" + thisitemarray[1] + "&classnames=userdept userdatainput",
success: function(data){
$('#'+id).html(data);
}
});
} else if (d === 3) {
userdata += "...";
}
答案 1 :(得分:0)
在查询设置中使用 async:false 参数
答案 2 :(得分:0)
@Sergey G - 谢谢,照顾它。以下是其他人的代码示例:
function getWhatever()
{ var strUrl =“”; //你需要调用的URL var strReturn =“”;
jQuery.ajax({ url:strUrl,success:function(html){strReturn = html;},async:false });
返回strReturn; }