gpt4 book ai didi

javascript - 如何使用 .ajax 数据初始化 knockoutjs View 模型

转载 作者:行者123 更新时间:2023-11-30 07:44:48 25 4
gpt4 key购买 nike

以下代码适用于硬编码数组 (initialData1),但是我需要使用 jquery .ajax (initialData) 来初始化模型,当我这样做时模型显示为空:

    $(function () {

function wiTemplateInit(winame, description) {
this.WIName = winame
this.WIDescription = description
}

var initialData = new Array;

var initialData1 = [
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
];
console.log('gridrows:', initialData1);

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
initialData.push(new wiTemplateInit(data.d[i].WiName,data.d[i].Description));
}
//console.log('gridrows:', initialData);
console.log('gridrows:', initialData);
}
});

var viewModel = function (iData) {
this.wiTemplates = ko.observableArray(iData);

};

ko.applyBindings(new viewModel(initialData));

});

我一直在尝试从 knockoutjs 网站上的示例开始工作,但是大多数示例都显示硬编码数据被传递到 View 模型。

最佳答案

确保您的“WIWeb.asmx/GetTemplates”返回具有精确结构的 json 对象数组 {WIName : '',WIDescription :''}并尝试使用这样的东西

    function wiTemplateInit(winame, description)
{
var self = this;
self.WIName = winame;
self.WIDescription = description;
}

function ViewModel()
{
var self = this;
self.wiTemplates = ko.observableArray();

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data)
{
var mappedTemplates = $.map(allData, function (item) { return new wiTemplateInit(item.WiName, item.Description) });
self.wiTemplates(mappedTemplates);

}
});
}

var vm = new ViewModel();

ko.applyBindings(vm);

关于javascript - 如何使用 .ajax 数据初始化 knockoutjs View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856803/

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