2019年6月5日 星期三

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

網頁端利用jquery提供的高階javascript方法getJSON或ajax取用其他網頁服務的寫法,資料傳收過程皆採用json格式:
  1.  
  2. $.getJSON( "http://host:port/path",
  3. {bookID:"1309088",format:"json"})
  4. .done(function( data ) {
  5. var output = "";
  6. for(var i in data.items){
  7. output ="<li>" + data.items[i].value + "," + data.items[i].id + "," + data.items[i].name + "</li>\n";
  8. $('#result').append(output);
  9. }
  10. })
  11. .fail(function() {
  12. window.alert("fail");
  13. });
  14. //--
  15. $.ajax({
  16. url: 'http://host:port/path', //存取Json的網址
  17. type: 'post',
  18. cache:false,
  19. dataType: 'json', // format expected from server
  20. contentType: 'application/json; charset=utf-8', // format sent to server
  21. data: JSON.stringify({bookID:"1309088}),
  22. success: function (data) {
  23. html = '<table>';
  24. i=1;
  25. $.each(data, function () {
  26. html += '<tr><td>' + data[i]['model'] + '</td>'
  27. ' + data[i]['epoch'] + '</td></tr>\n';
  28. i++;
  29. });
  30. html += '</table>';
  31.  
  32. document.getElementById("list_model").innerHTML = html;
  33. },
  34. error: function (xhr, ajaxOptions, thrownError) {
  35. document.getElementById("result").innerHTML =
  36. 'internal error(' + xhr.status + ',' + thrownError + '), try again...';
  37. }
  38. });