framework7 從ajax擷取資料然後重新整理

來源:互聯網
上載者:User

轉載自:http://www.680.com/Web/1609/webedit-43324.html

 簡單地介紹了 Template7 模板頁面的使用。當時模板頁面裡的列表資料是在 Framework7 初始化的時候就定義好的。

  但實際開發中,頁面資料並不都是一直不變的。而是通過 ajax 請求從外部,或者遠程伺服器上擷取資料。


  假設我們有個外部資料要載入:news.json


  {


  "title": "最新資訊",


  "news": [


  {


  "title": "歡迎訪問hangge.com",


  "date": "08-20"


  },


  {


  "title": "Framework7頁面緩衝設定",


  "date": "08-19"


  },


  {


  "title": "奧運健兒勇奪金牌",


  "date": "08-19"


  }


  ]


  }


  如何將擷取到的資料填充到 Template7 頁面上,通常有下面兩種方法。


  方法1:


  在 Framework7 初始化 preprocess 方法中,對載入列表頁面這個路由事件進行捕獲。先通過 ajax 擷取資料,資料擷取後使用模板進行填充後再繼續顯示。


  // 初始化 app


  var myApp = new Framework7({


  precompileTemplates: true,


  template7Pages: true, //pages啟用Template7


  template7Data: {


  },


  preprocess: function (content, url, next) {


  //判斷如果是跳轉到列表頁面


  if(url.indexOf("list.html")>=0){


  //先擷取資料


  $$.getJSON("data/news.json", function (data) {


  console.log(data);


  //模板編譯


  var compiledTemplate = Template7.compile(content);


  //模板資料載入


  next(compiledTemplate(data));


  });


  }else{


  //其他頁面按正常流程走


  next(content);


  }


  }


  });


  方法2:


  同樣是先在 preprocess 方法中,對載入列表頁面這個路由事件進行捕獲。通過 ajax 擷取資料後,將擷取到的資料放到 Template7 上下文資料中。再繼續載入頁面。


  // 初始化 app


  var myApp = new Framework7({


  precompileTemplates: true,


  template7Pages: true, //pages啟用Template7


  template7Data: {


  },


  preprocess: function (content, url, next) {


  //判斷如果是跳轉到列表頁面


  if(url.indexOf("list.html")>=0){


  //先擷取資料


  $$.getJSON("data/news.json", function (data) {


  console.log(data);


  //設定上下文資料


  Template7.data["page:list"] = data;


  //頁面繼續跳轉


  next(content);


  });


  }else{


  //其他頁面按正常流程走


  next(content);


  }


  }


  });


  方法3:


  不從連結直接跳轉。而是在連結的 click 事件裡先載入資料,資料載入完畢後將擷取到的資料放到 Template7 上下文資料中。最後再載入列表頁。


  (1)首頁跳轉連結 href 設為 #


  <a href="#" class="open-list">開啟列表頁面</a>


  (2)js相關代碼


  // 初始化 app


  var myApp = new Framework7({


  precompileTemplates: true,

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.