gpt4 book ai didi

javascript - 当我在 knockout 中从服务器加载数据时 undefined object

转载 作者:行者123 更新时间:2023-12-02 08:59:21 25 4
gpt4 key购买 nike

我从 knockout 中的服务器 Controller 加载一个列表并正确接收该列表,我也打印该列表,但是当将此数据放入多表 html 中时,出现错误“未捕获类型错误:无法读取属性‘push’”未定义的”...

但是如果我在按钮功能单击中执行此操作,一切都可以,但我需要不按任何按钮。

<!DOCTYPE html>
<html>
<head>
<tittle> <h1>Customers </h1></tittle>

</head>

<body>

<button data-bind="click: addItem">Add</button>
<p>List Names:</p>
<select multiple="multiple" height="8" data-bind="options:allItems"> </select>

<script type="text/javascript" src="/lib/knockout-3.5.0.js"></script>
<script src="/lib/jquery-3.4.1.js"></script>
<script src="/js/prueba.js"></script>

</body>

</html>

这是 .js

function ViewModel(){

this.allItems= ko.observableArray([]);
var list=[];

$.get("/customers", function(data) {

for(var i=0; i<data.length; i++){
list[i]={name:data[i].name, lastname:data[i].lastname};
alert(list[i].name);
alert(list[i].lastname);
}

console.log(this.allItems); // here "allItems" is undefined
this.allItems.push(list[0].name); //error
});

this.addItem= function(){

console.log(this.allItems); // here "allItems" is not undefined
this.allItems.push(list[0].name); //ok


};

};

ko.applyBindings(new ViewModel());

所以...我需要在开始时推送这个列表,有人帮忙吗?

最佳答案

因为你的thisget方法不是这个this您认为。您可以分配 thisself喜欢 var self = this;之前this.allItems = ko.observableArray([]);并在您的get中使用方法self.allItems相反 this.allItems .

关于javascript - 当我在 knockout 中从服务器加载数据时 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60281519/

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