2012-09-24 25 views
0

我在網上查找了2個多小時,試圖找到一個簡單的例子來說明如何從asp.net頁面加載的服務器代碼中填充jQuery變量。從服務器上加載jQuery變量加載

是我到目前爲止有:

我有一個按鈕,用於調用此jQuery代碼:

function GetListOfQuestions() { 
     $.ajax({ 
      type: "POST", 
      url: 'UserProfile.aspx/getQuestions', 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      error: OnAjaxError, 
      success: AjaxSucceeded 
     }); 
     //$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) { 
     // alert(data); 
     //}); 
    } 

    function AjaxSucceeded(result) { 

     alert(result); 

    } 

GetListOfQuestions調用服務器端:

[WebMethod] 
    public static List<Question> getQuestions(){ 

     var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey; 
     IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question 
     { 
      Uid = x.Uid, 
      Content = x.Content 
     }); 

     return list.ToList(); 
    } 

結果返回一個對象,如果我提醒它,所以它必須包含某種數據,但是我找不到任何可以在客戶端再次檢索數據的示例。

我不知道我現在正在做什麼是正確的(我是jQuery的新手)。那麼我怎麼能再次從結果變量中檢索數據呢?

+2

獲取Firefox +螢火蟲,使用控制檯查看您的對象及其內容。比用警報進行調試要容易得多。 – Erix

+2

剛剛嘗試過,非常好的工具,謝謝 – Timsen

回答

3

可能有更好的方法,但這是我所知道的一種方式:

[WebMethod] 
    public static string getQuestions(){ 

     var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey; 
     IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question 
     { 
      Uid = x.Uid, 
      Content = x.Content 
     }); 

     return new JavaScriptSerializer().Serialize(list.ToList()) 
    } 

在您的jQuery的方法,你可以

result = $.parseJSON(data) ; 

做一個console.log(result),看看如何通過結果迭代,應該只是一個for循環。

+0

嗯...沒有工作結果返回null – Timsen

+0

@Timsen oops list.ToList()....更新回答 –

+0

得到這個工作我的方式,但可以解釋爲什麼這個:的console.log(警報(result.d [0]。內容));返回內容?地獄的「d」來自哪裏? – Timsen

0

在頁面上放置一個隱藏字段,在其中設置變量值,稍後從js中讀取隱藏值。

另一種選擇是使用ScriptManager.RegisterStart UpScript直接將js寫入頁面。