[关闭]
@Lxyour 2018-02-06T14:40:06.000000Z 字数 1525 阅读 1247

JQuery第二节-Ajax与Json数据

JQuery 课程提纲


Ajax

JS原生XMLHttpRequest对象

  1. function loadXMLDoc() {
  2. var xmlhttp = new XMLHttpRequest();
  3. xmlhttp.open("GET", "ajax_info.txt", true);
  4. xmlhttp.send();
  5. xmlhttp.onreadystatechange = function() {
  6. if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
  7. if (xmlhttp.status == 200) {
  8. //callback
  9. document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
  10. }else if (xmlhttp.status == 400) {
  11. alert('There was an error 400');
  12. }else {
  13. alert('something else other than 200 was returned');
  14. }
  15. }
  16. };
  17. }

JQuery的Ajax

  1. $.ajax({
  2. url: 'xxx.json',
  3. type:'GET',
  4. success: function (data) {},
  5. error: function (err) {}
  6. })

JSON

一种轻量级的数据交换格式(一种数据格式)。

  1. {
  2. "code": 10000,
  3. "data": {
  4. "list": [
  5. {
  6. "id": 2101,
  7. "name": "锅贴",
  8. "price": 600,
  9. "sku": "P23564545756"
  10. },
  11. {
  12. "id": 2202,
  13. "name": "回锅肉",
  14. "price": 1500,
  15. "sku": "P23564545789"
  16. },
  17. {
  18. "id": 2503,
  19. "name": "芒果",
  20. "price": 750,
  21. "sku": "P23564545758"
  22. },
  23. {
  24. "id": 3604,
  25. "name": "苹果",
  26. "price": 450,
  27. "sku": "P23564545753"
  28. },
  29. {
  30. "id": 5605,
  31. "name": "荔枝",
  32. "price": 2000,
  33. "sku": "P23564545759"
  34. }
  35. ],
  36. "page": 1,
  37. "size": 10,
  38. "total": 5
  39. },
  40. "msg": "请求正确"
  41. }

示例

天气接口实战练习

调用天气接口。

  1. <div id="weather"></div>
  2. <script type="text/javascript">
  3. function getWeather() {
  4. var weatherAPI = "http://moguwang.net/api2.php?mod=weather";
  5. $.ajax({
  6. url: weatherAPI,
  7. dataType: 'script',
  8. scriptCharset: 'gbk',
  9. success: function (data) {
  10. console.log(window.SWther); // 请求结束后看这里输出的
  11. var cityData = window.SWther.lives[0];
  12. var tq = cityData.city + " " + cityData.weather + " " + cityData.temperature + "℃";
  13. $('#weather').html(tq);
  14. }
  15. })
  16. }
  17. getWeather()
  18. </script>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注