1. <script>
  2. window.onload = function(ev){
  3. var oBtn = document.querySelector(\'button\');
  4. // querySelector https://segmentfault.com/q/1010000014291684
  5. oBtn.onclick = function(ev1){
  6. // 1. 创建异步对象
  7. var xmlHttp = new XMLHttpRequest();
  8. /* 2. 设置请求方式和请求地址 open(method,url,async)
  9. method: 请求的类型 GET 或 POST
  10. url: 文件在服务器上的位置
  11. async: true(异步) false(同步)
  12. */
  13. xmlHttp.open("GET", "04-ajax-get.php", true);
  14. // 3. 发送请求
  15. xmlHttp.send();
  16. // 4. 监听状态的变化
  17. xmlHttp.onreadystatechange = function(ev2){
  18. /*
  19. 0: 请求未初始化
  20. 1: 服务器连接已建立
  21. 2: 请求已接收
  22. 3: 请求处理中
  23. 4:请求已完成,且相应已就绪
  24. */
  25. if(xmlHttp.readyState === 4){
  26. //判断是否请求成功
  27. if(xmlHttp.status >= 200 && xmlHttp.status < 300 || xmlHttp.status === 304){
  28. // 5. 处理返回的结果
  29. console.log(\'接收到服务器返回的数据\');
  30. }else{
  31. console.log(\'没有接收到服务器返回的数据\');
  32. }
  33. }
  34. }
  35. }
  36. }
  37. </script>
  38. </head>
  39. <!-- 使用Ajax更新数据和 不使用Ajax的区别:
  40. 不使用ajax更新数据,会重新加载整个页面
  41. (例如 淘宝 输入关键字,搜索)
  42. 使用ajax更新数据, 不会重新加载整个页面,只更新某些部分
  43. (例如 淘宝搜索栏- 输入关键字 自动更新下拉提示框的内容 )-->
  44. <body>
  45. <button>发送请求</button>
  46. </body>

 

版权声明:本文为carpenterzoe原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/carpenterzoe/p/10386854.html