2015年4月16日 星期四

[MobileWeb]網路掛號Prototype-3(jsonp、HTML5 localStorage)

我們把localStorage當成profile的暫存區,可以有效減少網路的傳輸次數,以下只是簡單的範例~
1.模擬遠端資料(jsonp)
JavaScript
function simRemoteData()
{
  var remoteData = [
    {"醫師": "柯X哲", "科別": "外科", "時段": "上午(08:30~11:30)"},
    {"醫師": "邱X逹", "科別": "外科", "時段": "下午(13:30~17:00)"},
    {"醫師": "沈X雄", "科別": "內科", "時段": "上午(08:30~11:30)"},
    {"醫師": "賴X德", "科別": "內科", "時段": "上午(08:30~11:30)"},
    {"醫師": "柯X銘", "科別": "牙科", "時段": "上午(08:30~11:30)"},
    {"醫師": "涂X哲", "科別": "內科", "時段": "夜診(08:30~11:30)"}
  ];
  var remoteJsonpData = { jsonData: JSON.stringify(remoteData), delay: 3 };
  return remoteJsonpData;
}

2.接收遠端資料(jsonp)並存入本地端 Local Storage(HTML5)
JavaScript
function getRemoteData()
{
  $.ajax({
    type: "GET",
    url: "//jsfiddle.net/echo/jsonp/",
    dataType: "jsonp",
    data: simRemoteData(),
    cache: false,
    error: function (jqXHR, textStatus, errorThrown) {
      console.log(textStatus + " - " + errorThrown);
    },
    success: function (data, textStatus, jqXHR) {
      console.log(textStatus + " - " + data);
          
      var jsonData = JSON.parse(data.jsonData);
      if (jsonData) {
        localStorage.查詣資料 = JSON.stringify(jsonData);

        var _targetList = $("#查詢時間List");
        var _jsonData = getLocalData();
        display查詣資料Data(_targetList, _jsonData);
      }
    }
  });
}

3.取得本地端 Local Storage(HTML5)資料
JavaScript
function getLocalData()
{
  var jsonData = localStorage.查詣資料;
  if (!jsonData){
    jsonData = {};
    localStorage.查詣資料 = JSON.stringify(jsonData);
  } else {
    jsonData = JSON.parse(jsonData);
  }
  return jsonData;
}

4.顯示"查詣資料"頁面資料
JavaScript
function display查詣資料Data(_targetList, _jsonData)
{
  if (_jsonData) {
    var markup = "";
    var dataLength = _jsonData.length;
    for (var i = 0; i < dataLength; i++) {
      markup += "
  • " + _jsonData[i].醫師 + "

    " + _jsonData[i].科別 + "
  • "; } _targetList.html(markup).listview({ autodividers: true, autodividersSelector: function ( li ) { return li.data("時段"); } }).listview("refresh"); } }

    ※ 原始碼及執行預覽(jsFiddle): http://jsfiddle.net/L8su2/810/
    參考資料
    [1] Create a CRUD web app using JQuery Mobile and LocalStorage