如何使用.ajax数据初始化knockoutjs视图模型

时间:2012-01-13 20:27:50

标签: javascript knockout.js

以下代码适用于硬编码数组(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网站上的示例,但是大多数示例都显示硬编码数据被传递给视图模型。

2 个答案:

答案 0 :(得分:7)

确保您的“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);

答案 1 :(得分:0)

如果您向我们展示您的浏览器日志,我们可以详细说明您的问题(特别是帖子和回复)。我为您准备了一个简单的示例,说明如何使用ajax加载数据,绑定模板,使用操作对其进行操作并保存。

希望这有助于解决您的问题:http://jsfiddle.net/gurkavcu/KbrHX/

摘要:

 // This is our item model 
function Item(id, name) {
   this.id = ko.observable(id);
   this.name = ko.observable(name);
}

// Initial Data . This will send to server and echo back us again
var data = [new Item(1, 'One'),
            new Item(2, 'Two'),
            new Item(3, 'Three'),
            new Item(4, 'Four'),
            new Item(5, 'Five')]

// This is a sub model. You can encapsulate your items in this and write actions in it
var ListModel = function() {    

   var self = this;    
   this.items  = ko.observableArray();
   this.remove = function(data, parent) {
        self.items.remove(data);
   };
   this.add    = function() {
        self.items.push(new Item(6, "Six"));
   };
   this.test   = function(data, e) {
       console.log(data);
       console.log(data.name());
   };
   this.save   = function() {        
       console.log(ko.mapping.toJSON(self.items));
   };   
}

// Here our viewModel only contains an empty listModel
function ViewModel() {
    this.listModel = new ListModel();
};

var viewModel = new ViewModel();

$(function() {
    $.post("/echo/json/", {
        // Data send to server and echo back
        json: $.toJSON(ko.mapping.toJS(data))
    }, function(data) {

    // Used mapping plugin to bind server result into listModel
    // I suspect that your server result may contain JSON string then 
    // just change your code into this
    // viewModel.listModel.items = ko.mapping.fromJSON(data); 

    viewModel.listModel.items = ko.mapping.fromJS(data);

    ko.applyBindings(viewModel);
});
})