簡體   English   中英

使用JQuery Mobile AJAX加載JSON數據

[英]Loading JSON data using JQuery Mobile AJAX

嗨,我正在為我的WordPress博客開發第一個移動應用程序。 我已經在WordPress中安裝了JSON API插件。 我可以使用“ example.com/api/get_recent_posts/”訪問JSON數據。

我創建了一個包含2頁的HTML頁面。 第一頁只是帶有按鈕的列表。 我要在第二頁上從JSON加載數據。 我研究了一些JQuery Mobile,並了解到加載動態內容的最佳方法是AJAX。

我看到了很多例子,其中pagebeforeshow,pageinit與$ .getJSON函數或低於$ .ajax函數的結合:

$.ajax({
    url: '',
    type: 'GET',
    error : function (){ document.title='error'; }, 
    success: function (data) {
        //
    }
});

請僅提供有關如何使用JQuery Mobile AJAX函數加載JSON提要的指南。

HTML代碼:

<!-- Page: Home -->
    <div id="home" data-role="page">
        <div data-role="header">
            <h1>Menu</h1>
        </div><!-- /header -->
        <div data-role="listview">
            <p>This page is just a simple static page</p>
            <p><a href="#blogposts" class="ui-btn ui-shadow ui-corner-all" id="devotionclick" data-role="button">Load my blogs</a>
        </div><!-- links -->
    </div><!-- page -->

<!-- Page: Blog Posts -->
    <div id="blogposts" data-role="page">
        <div data-role="header" data-position="fixed">
            <h2>My Blog Posts</h2>
        </div><!-- header -->
        <div data-role="content">
            <ul id="postlist"> </ul><!-- content -->
        </div>
        <div class="load-more">Load More Posts...</div> 
    </div><!-- page -->

據我所知(並且可能已經關閉),JQuery Mobile只是常規JQuery的擴展,其中包含一些特定於移動設備的其他事件和方法。 只要您也加載普通版本的JQ,仍然可以使用$ .ajax和$ .getJSON來熟悉JQuery。

如果您選擇JQuery Mobile希望提高移動性能,請嘗試ZeptoJS

$ .getJSON是$ .ajax API的包裝,帶有一些預設參數。 我幾乎只使用$ .getJSON,除非我需要對請求進行一些自定義(同步而不是異步,...)

如果您在第二頁上需要一些東西,請嘗試以下操作:

<div id="blogposts" data-role="page">
<script>
$(document).on('pagebeforeshow', '#blogposts', function() {
     $.getJSON('http://example.com/api/get_recent_posts/', null, function(data) {
         $.each(data, function(p, post) {
              console.log(post.title); //Or whatever JSON keys you get back in return
              //Add them to a listview, or whatever you need to do.
         });
     });

});
</script>
<!-- rest of your page goes here -->
</div>

請注意,在實例化pagebeforeshow調用時,您想指定頁面ID。

說得通?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM