2019年6月5日 星期三

jquery getJSON and ajax functions for calling JSON-based web services

網頁端利用jquery提供的高階javascript方法getJSON或ajax取用其他網頁服務的寫法,資料傳收過程皆採用json格式:

  $.getJSON( "http://host:port/path",
      {bookID:"1309088",format:"json"})
    .done(function( data ) {
      var output = "";
      for(var i in data.items){
         output ="<li>" + data.items[i].value + "," + data.items[i].id + "," + data.items[i].name + "</li>\n";
         $('#result').append(output);
      }
    })
    .fail(function() {
       window.alert("fail");
    });
  //--
  $.ajax({
      url: 'http://host:port/path',   //存取Json的網址
      type: 'post',
      cache:false,
      dataType: 'json', // format expected from server
      contentType: 'application/json; charset=utf-8', // format sent to server
      data: JSON.stringify({bookID:"1309088}),
    success: function (data) {
      html = '<table>';
      i=1;
      $.each(data, function () {
          html +=  '<tr><td>' + data[i]['model'] + '</td>'
                   ' + data[i]['epoch'] + '</td></tr>\n';
         i++;
      });
      html += '</table>';

      document.getElementById("list_model").innerHTML = html;
    },
    error: function (xhr, ajaxOptions, thrownError) {
      document.getElementById("result").innerHTML =
        'internal error(' + xhr.status + ',' + thrownError + '), try again...';
    }
  });