gpt4 book ai didi

javascript - 无法读取未定义 jquery 的属性 'length'

转载 作者:行者123 更新时间:2023-11-28 01:42:34 24 4
gpt4 key购买 nike

我使用 ajax 从 C# Web 方法获取一个列表(下面的代码),该列表返回正常,但在成功方法完成后,它给我一个错误 - (无法读取未定义的属性“长度”) 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");
}
});

};

enter image description here

上面的方法被下面的方法调用。

    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);
};

编辑:

上面第一段代码中警报中的数据显示如下 enter image description here

在 Chrome 调试器中: enter image description here

最佳答案

因为 getMainParentMenus 使用 AJAX,所以它是异步的。调用 getMainParentMenus 后的下一行代码将在 AJAX 调用的 .success 部分之前执行,因此它将被执行在填充 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");
}
});

};

现在你可以这样调用它:

var html = "<div id='accordian'> ddd";

getMainParentMenus(function() {
$.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>";
});
});
});

关于javascript - 无法读取未定义 jquery 的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com