我从C#web方法获取一个带有ajax的列表(下面的代码),列表返回正常,但是在成功方法完成后,它给了我一个错误 - (无法读取未定义的属性'length') jquery(下面的截图)
我错过了什么吗?
function getMainParentMenus() {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
以上方法通过以下方法调用。
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
// var parentMenus = getMainParentMenus();
getMainParentMenus();
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
};
编辑:
上面第一段代码中警报中的数据就像这样显示
并在chrome调试器中:
答案 0 :(得分:1)
因为getMainParentMenus
正在使用AJAX,所以它是异步的。调用getMainParentMenus
后的下一行代码将在 AJAX调用的.success
部分之前执行,因此它将在之前执行 {{已填充1}}。
有几种方法可以解决这个问题,一种方法是将回调函数传递给parentMenuss
,如下所示:
getMainParentMenus
现在你可以这样称呼它:
function getMainParentMenus(myCallback) {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
if (callback && typeof(callback)==="function") {
callback();
}
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
答案 1 :(得分:0)
用于呈现菜单的代码正在getMainParentMenus();
之后立即执行.Javascript不等待ajax调用完成,然后再转到下一个块。正如其他人在评论中提到的那样,它是异步操作的。
在尝试显示数据之前,您的代码必须等待ajax调用完成。
jQuery支持延迟执行和promises,因此您可以创建在其他代码完成之前不会执行的代码。这是处理异步操作的首选方法。
试试这个:
function getMainParentMenus() {
var request = $.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
return request;
}
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
getMainParentMenus().success(function (result) {
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
});
}