2014-01-08 102 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

自從象牙塔或誰把這個「擱置」,因爲有人不喜歡我的頭銜,我猜它已經死了。不過,我想把這個標記作爲答案,因爲它幫助我理解了約翰隊長的答案。謝謝你的幫助,哈坦。祝我好運搞清楚爲什麼它仍然沒有工作:) –