为什么这个js / jquery / knockout不起作用?

时间:2014-01-08 21:31:52

标签: javascript jquery knockout.js

我(尝试)在这里一次学习javascript,jquery和knockout。我终于得到了一个发回JSON的web服务。但我无法显示数据。有人能告诉我为什么这不起作用?没有错误被抛出。一旦它运行,它就没有任何形式。标题说明了一切:它不起作用,没有解释发生了什么。我需要知道为什么不。

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="EditLTC2.aspx.cs" Inherits="RaterWeb.EditLTC2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="formLayout">
        <label for="txtInsuredName">Insured Name:</label>
        <input data-bind="value: InsuredName" />
    </div>
    <script>
        $(document).ready(function ()
        {
            var self = this;

            // Load selected quote from the JSON service
            SelQuote = $.getJSON("http://localhost:46648/LTCJSON.svc/getLTCWithIDs/4/");

            // assign to AppViewModel
            function AppViewModel()
            {
                this.InsuredName = ko.observable(SelQuote.InsuredName);
            }

            ko.applyBindings(new AppViewModel());
        });
    </script>
</asp:Content>

2 个答案:

答案 0 :(得分:0)

getJSON是异步调用。因此,绑定viewModel,然后更新getJSON回调接收到的值

$(document).ready(function ()
    {
        var self = this;
        var appViewModel 
        // Load selected quote from the JSON service


        // assign to AppViewModel
        function AppViewModel()
        {
            this.InsuredName = ko.observable("");
        }
        var appViewModel = new AppViewModel();
        ko.applyBindings(appViewModel);
        $.getJSON("http://localhost:46648/LTCJSON.svc/getLTCWithIDs/'4'/",  
        { 
           success: function(data) {
              appViewModel.InsuredName(data);
           }
        });
    });

答案 1 :(得分:0)

如前所述$ .getJSON不会从ajax调用返回数据,而是返回一个promise。您需要为其附加成功处理程序,然后像这样更新InsuredName observable的值

$(document).ready(function ()
    {
        function AppViewModel()
        {
            this.InsuredName = ko.observable();
        }
    ko.applyBindings(viewModel );

    var self = this,
    viewModel = new AppViewModel();

    // Load selected quote from the JSON service
    SelQuote = $.getJSON("http://localhost:46648/LTCJSON.svc/getLTCWithIDs/4/");
    SelQuote.success(function(data){
      this.InsuredName(data);
    });



    });