js原生ajax请求:get和post

末蓝、 2023-07-06 06:12 107阅读 0赞

‘get’请求

  1. <script>
  2. window.onload=funciton(){
  3. // 创建ajax对象
  4. var xhr=new XMLHttpRequest();
  5. //配置参数 需要两个1:get;2:url 请求地址
  6. xhr.open('get','url');
  7. //发送请求
  8. xhr.send();
  9. //接收数据
  10. xhr.onload=function(){
  11. //接收到的数据
  12. console.log(xhr.responseText);
  13. }
  14. }
  15. </script>

‘post’请求

需要设置请求头:

xhr.setRequestHeader(‘Content-Type’,‘application/json’)

  1. <script>
  2. window.onload=funciton(){
  3. // 创建ajax对象
  4. var xhr=new XMLHttpRequest();
  5. //配置参数 需要两个1:get;2:url 请求地址
  6. xhr.open('get','url');
  7. //设置请求头 post请求必须要设置的
  8. xhr.setRequestHeader('Content-Type','application/json');
  9. //发送请求
  10. xhr.send();
  11. //接收数据
  12. xhr.onload=function(){
  13. //接收到的数据
  14. console.log(xhr.responseText);
  15. }
  16. }
  17. </script>

‘post’请求示例

工作中post请求用的多,所以演示一个post示例

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script>
  8. window.onload = function () {
  9. var btn = document.getElementById("btn");
  10. var username=document.getElementById("username");
  11. var pssword=document.getElementById("password");
  12. var show=document.getElementById("show");
  13. btn.onclick = function(){
  14. var usernameValue=username.value;
  15. var passwordValue=password.value;
  16. //需要传的数据
  17. var obj={ "username":usernameValue,"password":passwordValue};
  18. // 创建ajax post请求的五个步骤
  19. //1:创建Ajax异步对象
  20. var xhr = new XMLHttpRequest();
  21. //2:配置请求方式 请求地址
  22. xhr.open('post', 'http://192.168.1.3:8081/user/login');
  23. // 3:设置请求头
  24. xhr.setRequestHeader('content-type', 'application/json');
  25. //4:转换为JSON数据对象 JSON.parse() 传数据之前要干嘛呢 转换为json数据格式
  26. xhr.send(JSON.stringify(obj));
  27. // 5:接收数据
  28. xhr.onload = function () {
  29. //6:判断是否接收成功
  30. if(xhr.status==200 && xhr.readyState==4){
  31. // 拿到数据并转换为js对象
  32. var info=JSON.parse(xhr.responseText);
  33. console.log(info)
  34. show.innerHTML+="姓名:"+info.data.username+"<br>";
  35. show.innerHTML+="年龄:"+info.data.age+"<br>";
  36. show.innerHTML+="密码:"+info.data.password+"<br>";
  37. show.innerHTML+="性别:";
  38. show.innerHTML+=(info.data.gender==1)?'男':'女';
  39. }else{
  40. alert("数据请求出错!")
  41. }
  42. }
  43. }
  44. }
  45. </script>
  46. </head>
  47. <body>
  48. 用户名:<input id="username" type="text" autocomplete="off"><br>
  49. 密码:<input id="password" type="text"><br>
  50. <button id="btn">数据请求</button><br>
  51. 用户信息:<br>
  52. <h1 id="show"></h1>
  53. </body>
  54. </html>

示例图片

显示的数据就是请求过来的数据
在这里插入图片描述

发表评论

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

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

相关阅读