繁体   English   中英

Ajax从多个JSON来源加载数据

[英]Ajax load data from multiple JSON sources

我正在Razor2中使用ASP MVC4。 我正在尝试使用Javascript检索JSON数据并选择我要显示的属性。 每个线程都有其自己的JSON文件,我一次显示15个线程。 我无法一次获取所有数据,这会减慢页面加载时间。 因此,我认为客户端会很好,因为它不是敏感数据。

这是我的代码:

 public static PagedList<PiFDetailsModel> GetPagedThreads(int skip, int take)
    {
        using (var context = new PiFDbDataContext())
        {
            // refactor consideration...make this a pre-compiled query
            var threads = context.Threads
              .OrderBy(c => c.CreatedDate).Skip(skip).Take(take).ToList();

            var threadsCount = threads.Count();

            var details = new List<PiFDetailsModel>();
            foreach (Thread thread in threads)
            {
                var model = new PiFDetailsModel();

                var games = new List<Game>();
                // Make this AJAX instead.
                string text;
                try
                {
                    text = Utilities.GetThreadInfo(thread.ThingID)[0].data.children[0].data.selftext_html;
                    text = text.Replace("\n\n", "<br /><br />").Replace("\n", "<br />");
                }
                catch
                {
                    // TODO Handle exceptions better.
                    text = "Reddit is currently down or too busy, cannot retrieve information at this time";
                }

                foreach (ThreadGame game in thread.ThreadGames)
                {
                    if (games.Any(x => x.Name == game.Game.Name))
                    {
                        games.Find(x => x.Name == game.Game.Name).Count += 1;
                    }
                    else
                    {
                        var simpleGame = game.Game;
                        simpleGame.Count = 1;
                        games.Add(simpleGame);
                    }
                }

                model.Games = games;
                model.GameCount = thread.ThreadGames.Count;
                model.ThreadTitle = thread.Title;
                model.Username = thread.User.Username;
                model.CreatedDate = thread.CreatedDate;
                model.ThreadID = thread.ThingID;

              //  model.SelfText = new HtmlString(text);

                details.Add(model);
            }

            return new PagedList<PiFDetailsModel>
            {
                Entities = details,
                HasNext = skip + 10 < threadsCount,
                HasPrevious = skip > 0
            };
        }
    }

[OutputCache(Duration = 60 * 5)]
        public static dynamic GetThreadInfo(string thingID)
        {
            string uri = string.Format("http://www.reddit.com/{0}/.json", thingID);
            var connect = WebRequest.Create(new Uri(uri)) as HttpWebRequest;

            connect.UserAgent = "r/playitforward site by /u/sevenalive";

            // Do the actual connection
            WebResponse response = connect.GetResponse();

            string resp;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                resp = reader.ReadToEnd();
            }

            return new JavaScriptSerializer().Deserialize<dynamic>(resp);
        }

指数:

@foreach (var item in Model)
{
    <div class="pif">
        <div class="left">
            <div class="title"><a href="/PiF/@item.ThreadID">@item.ThreadTitle</a></div>
            <div class="description">
                <div class="expandable">
                    <p>@item.SelfText</p>
                </div>
            </div>
            <div class="createdTime">
                <strong>@Html.TimeAgo(@item.CreatedDate)</strong>
            </div>
            <div class="createdBy">
                @if (item.Games.Count() == 1)
                {
                   @item.Games.Single().Name
                }
                else
                {
                    <text>@item.GameCount games</text>
                }
                being given by <a href="@string.Format("http://reddit.com/u/{0}", item.Username)">@item.Username</a>
            </div>
        </div>
        <div class="left">
            <ul class="games">
                      @foreach (var game in item.Games)
                      {
                          <li>
                              <a href="@game.StoreUrl" title="@game.Name">@game.Name</a> <span style="color:#b5b8be; font-weight:600">@string.Format("({0}P)", game.PointWorth)</span>
                              @if (game.Count > 1)
                              {
                                  <span style="color:#b5b8be; font-weight:600">(@game.Count copies)</span>
                              }
                          </li>
                      }
                  </ul>
        </div>
        <div class="clearBoth"></div>
    </div>
}

我尝试进行一些搜索,但是找不到我想要的任何示例。 我认为javascript(可能是JQuery)将是最好的方法。 我是Web开发的新手,因此非常感谢您提供详细的示例。 整个代码库都是开源的,我可以使用帮助,所以如果您需要,请分叉! https://github.com/sevenalive/PlayItForward

function GetSelfText(thingId) {
    $.getJSON("http://www.reddit.com/r/playitforward/comments/" + thingId + "/.json?jsonp=?", { id: thingId }, function (data) {
        var tempHtml = $('<div/>').html(data[0].data.children[0].data.selftext_html).text();
        $("#selfText-" + thingId).html(tempHtml);
    })
}

<div class="description" id="selfText-@item.ThreadID">
                        <script type="text/javascript">
                            $(document).ready(function () { GetSelfText('@item.ThreadID'); });
                        </script>
            </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM