knockoutjs使用AJAX的表单示例

时间:2013-09-18 05:08:30

标签: jquery ajax forms knockout.js

我正在尝试使用Knockoutjs创建一个简单的表单,它将通过AJAX传递一些用户信息。
有人有一个有三个字段(名字,姓氏,邮政编码)的例子。如果可用,它可以从服务器获取这三个字段或加载空白。然后将这三个字段放在一个对象中并使用AJAX发布。

    function UserInfo(data){
       this.firstname = ko.observable(data.firstname);
       this.lastname = ko.observable(data.lastname);
       this.postal-code = ko.observable(data.postal-code);
     }
     function UserInfoViewModel()
     {
        //Do stuff here to save up
     }

我真的只是在寻找一个简单的例子。但每次我看它都是加载数组的东西。这些示例似乎只是跳过了一些AJAX的标准表单示例。如果我能看到一种基本上形成粗糙形式的最佳实践方法,我可以使用它。

2 个答案:

答案 0 :(得分:1)

要简化代码,您应该使用ko.mapping。 ko.mapping允许您将普通对象“转换”为具有可观察对象的对象。

在你的情况下会那样:

var UserInfo = function (data) {
    // add a self property, it is really helpful when you need to refer the current viewmodel (eg in ajax callback) 
    var self = this;
    // ko.mapping.fromJS creates for all properties in data an observable in self.
    ko.mapping.fromJS(data, {}, self);        
    // the above line do that : 
    /*
        self.firstname = ko.observable(data.firstname);
        ...
    */

    self.save = function () {
        // ko.mapping.toJS converts the viewmodel (with observables) into plain object.
        var raw = ko.mapping.toJS(self);
        $.ajax('url', { data: raw })
            .done(function () {
            // in this context 'this' refers to window, but you can use 'self'.
            alert("success");
        });
    };
};

var initialData = {
    firstname: 'firstname ',
    lastname: 'lastname',
    'postal-code': 'postal-code'
};

var ui = new UserInfo(initialData );

我希望它有所帮助。

答案 1 :(得分:1)

查看:

<button data-bind="click : $data.save">Save</button>  

型号

self.save()
{
    $.ajax({
        url: "url/saveUser",
        type: "GET",
        data: {
           firstname : self.firstname(),
           lastname: self.lastname(),
           postalCode: self.postalCode()
        },
        success: function(data)
        {
            alert("OK!")
        },
        error: function(jqXHR, exception)
        {
           alert("Not OK!")    
        }
}  

JSFiddle DEMO