framework7 從ajax獲取數據然後刷新

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

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

blob.png

  但實際開發中,頁面數據並不都是一直不變的。而是通過 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,


  template7Pages: true, //pages啓用Template7


  template7Data: {


  }


  });


  // 爲便於使用,自定義DOM庫名字爲$$


  var $$ = Dom7;


  // 添加首頁視圖


  var mainView = myApp.addView('.view-main', {


  // 讓這個視圖支持動態導航欄


  dynamicNavbar: true


  });


  //跳轉鏈接點擊


  $$('.open-list')。on('click', function () {


  //先獲取數據


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


  console.log(data);


  //設置上下文數據


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


  //頁面跳轉


  mainView.router.loadPage("list.html");


  });


  });

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章