我有AJAX这个问题。我运行代码并且在打印代码时未定义ajaxString,即使在返回语句之前几乎调用了Ajax代码。当我在HTML生成和打印之后尝试检索AJAX时,定义了AJAX,这让我觉得在AJAX有机会完成之前调用了返回。有什么方法吗?这是我目前的代码:
var ajaxHTML;
function runCode(str) {
if (str == 'SubmitB' || str == 'SubmitC' || str == 'SubmitD') {
generateHTML(str);
}
else {
$('#Holder1').html("");
$('#Holder2').html("");
$("#container_demo").fadeOut(500);
setTimeout(function(){$("#menu_container").html(generateHTML(str))},500);
$("#container_demo").fadeIn(500);
}
}
function generateHTML(source){
if (source =='d') {
return makeSchoolComboBox() + "Please Select a Level: <select id='selectedLevel'><option value='level1'>l1</option><option value='level2'>l2</option><option value='level3'>l3</option><option value='level4'>l4</option></select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button><button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>";
}
function makeSchoolComboBox() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function (data) {
ajaxHTML = data;
}
});
return ajaxHTML;
}
答案 0 :(得分:2)
由于AJAX是异步的,因此您无法调用它,然后在呼叫仍在进行时直接返回。您需要在成功回调中填充菜单容器,如下所示......
function runCode(str) {
if (str == 'SubmitB' || str == 'SubmitC' || str == 'SubmitD') {
generateHTML(str);
}
else {
$('#Holder1').html("");
$('#Holder2').html("");
$("#container_demo").fadeOut(500);
makeSchoolComboBox();
}
}
function makeSchoolComboBox() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function (data) {
$("#menu_container").html(data + "Please Select a Level: " +
"<select id='selectedLevel'>" +
"<option value='level1'>l1</option>" +
"<option value='level2'>l2</option>" +
"<option value='level3'>l3</option>" +
"<option value='level4'>l4</option>" +
"</select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button>" +
"<button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>").fadeIn(500);
}
});
}
答案 1 :(得分:0)
ajax查询是异步的
function makeSchoolComboBox(next) {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: next
});
}
并将其作为
运行makeSchoolComboBox(function(ajaxHTML){
//manipulations with here
})
或者您可以在async: false
中传递$.ajax
,但在这种情况下处理ajax请求时所有停止
答案 2 :(得分:0)
如果你需要保留你正在使用的结构(我将generateHTML和makeSchoolComboBox放到一个函数中以保持简单),那么你可以使用promises。
您的代码将成为:
function generateHTML(source){
if (source =='d') {
makeSchoolComboBox().then(function(data) {
return data + "Please Select a Level: <select id='selectedLevel'><option value='level1'>l1</option><option value='level2'>l2</option><option value='level3'>l3</option><option value='level4'>l4</option></select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button><button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>";
});
}
}
function makeSchoolComboBox() {
var d = new $.Deferred();
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function(data) {
return d.resolve(data);
}
});
}