2014-01-08 183 views
-1

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

<%@ 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> 
+1

'$ .getJSON'是异步的。 – elclanrs

+2

...并且它不返回它提取的数据。它返回一个承诺对象。 – Pointy

+1

** **的DUP:http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs

回答

0

getJSON是一个异步调用。所以,你绑定,当它由回调收到的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); 
      } 
     }); 
    }); 
+0

0x800a1391 - JavaScript的运行时错误:“SelQuote”是未定义 –

+0

更新的insuredname变量 –

+0

创作得到正确设置支架,该停止引发错误之后。但是当我闯入成功:函数时,数据变量是未定义的,所以没有数据需要填充。 –

0

提到$ .getJSON不从Ajax调用返回回数据的视图模型,然后更新该值,而是返回一个承诺。您需要附加一个成功处理程序,然后更新InsuredName可观察值,如

$(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); 
    }); 



    }); 
+0

0x800a1391 - JavaScript的运行时错误: 'InsuredName' 是未定义 –

+0

遗憾的是,本来应该viewModel.InsuredName(数据); –

+0

自从象牙塔或谁把这个“搁置”,因为有人不喜欢我的头衔,我猜它已经死了。不过,我想把这个标记作为答案,因为它帮助我理解了约翰队长的答案。谢谢你的帮助,哈坦。祝我好运搞清楚为什么它仍然没有工作:) –