代码之家  ›  专栏  ›  技术社区  ›  Timsen

加载时从服务器端填充jQuery变量

  •  0
  • Timsen  · 技术社区  · 14 年前

    我在网上找了两个多小时,试图找到一个简单的例子,说明如何在加载asp.net页面时从服务器端代码中填充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 回复  |  直到 14 年前
        1
  •  3
  •   Lews Therin    14 年前

    还有更好的方法,但这是我所知道的一种方法:

    [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循环。

        2
  •  0
  •   Andrew Barber Eric Lafortune    14 年前

    在你的页面上放一个隐藏字段,在那里设置变量值,然后从js中读取隐藏值。

    另一种选择是使用ScriptManager.RegisterStart-UpScript将变量直接作为js写入页面。