Ajax ajax原生-xhr对象处理get请求

本是古典 何须时尚 2021-07-24 11:38 607阅读 0赞

前台:

  1. <html>
  2. <head>
  3. <meta charset="utf-8">
  4. <title></title>
  5. <script src="jquery-3.4.1.js"></script>
  6. </head>
  7. <body>
  8. <button>发送请求</button>
  9. <script>
  10. var btn=document.querySelector('button');
  11. btn.onclick=function()
  12. {
  13. //创建xhr对象
  14. var xhr=new XMLHttpRequest();
  15. //监听请求是否成功
  16. xhr.onreadystatechange=function()
  17. {
  18. //通过readyState属性的值,判断当前请求状态
  19. if(xhr.readyState==4)
  20. {
  21. console.log("已接受");
  22. //通过status属性来判断前台接收状态
  23. if(xhr.status==200)
  24. {
  25. console.log(xhr.statusText);
  26. //此时表明真正接收到了数据
  27. console.log(xhr.responseText);
  28. console.log(JSON.parse(xhr.responseText));
  29. }
  30. }
  31. };
  32. //发送ajax
  33. //设置发送
  34. //无参get
  35. xhr.open('get','3.php',true);
  36. //有参get
  37. xhr.open('get','3.php?uame='+uname+'&upwd='+upwd);
  38. //开始发送
  39. xhr.send(null);
  40. }
  41. </script>
  42. </body>
  43. </html>

后台:

  1. <?php
  2. $success=array('mes'=>'ok');
  3. echo json_encode($success);
  4. ?>

发表评论

表情:
评论列表 (有 0 条评论,607人围观)

还没有评论,来说两句吧...

相关阅读