使用Knockout.js从表单中获取或发送数据 [英] Fetching or sending data from a form using knockout.js

查看:336
本文介绍了使用Knockout.js从表单中获取或发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Knockout中的新手,也是前端设计师,所以我需要坦白地说.

Newbie in Knockout, also a front-end designer so I need plain talk.

我有一个需要发送到数据库,然后在以后从数据库中检索的表格.

I have a form that I need to send to the database and then retrieve from the database later.

请以非常简单的方式说明如何制作一个有效的示例来说明如何保存和发布表格?

Please explain in very simple terms how to produce a working example to illustrate saving and posting a form?

摘自教程: http://knockoutjs.com/documentation/json-data.html 我了解有关获取和发送json数据的知识. json数据如何与表单匹配?什么是映射?是否有一个插件或简单示例说明如何将json数据映射回我的表单?基本上,我该怎么做下面的敲除代码示例中的注释?

From knockout tutorial: http://knockoutjs.com/documentation/json-data.html I understand about getting and sending json data. How is the json data being matched to the form? What is mapping and is there a plugin or easy example of how to map the json data back to my form? Basically, how do I do what is commented inside the knockout code examples below?

获取数据:

$.getJSON("/some/url", function(data) {
    // Now use this data to update your view models,
    // and Knockout will update your UI automatically
})

发送数据:

var data = /* Your data in JSON format - see below */;
$.post("/some/url", data, function(returnedData) {
    // This callback is executed if the post was successful    
})

推荐答案

简单形式

 <form data-bind="submit: onSubmit">
    <input data-bind="value : firstName"/>
    <input data-bind="value : lastName"/>
    <input type="submit" text="Submit!"/>
</form>
Response: <span data-bind="text : response"></span>

简单视图模型

var viewModel = new function()
{
    var self = this;
    self.firstName = ko.observable("default first");
    self.lastName = ko.observable("default last");
    self.responseJSON = ko.observable(null);
    self.onSubmit = function() 
    {
        var data = JSON.stringify(
            {
                first : self.firstName(), last : self.lastName()        
            }); // prepare request data
        $.post("/echo/json", data, function(response) // sends 'post' request
        {
            // on success callback
            self.responseJSON(response);
        })
    }
}

ko.applyBindings(viewModel);  

JSFiddle演示版

这篇关于使用Knockout.js从表单中获取或发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆