Ajax中发送get、post请求以及服务端响应json数据

1.发送get请求

get.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax Get 请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border:solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        //获取button元素
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        //绑定事件
        btn.onclick = function() {
            //1.创建对象
            const xhr = new XMLHttpRequest();
            //2.初始化,设置请求方法和url
            xhr.open('GET', 'http://127.0.0.1:8000/server');
            //3.发送
            xhr.send();
            //4.事件绑定,处理服务端返回的结果
            //on 当...时候
            //readystate是xhr对象中的属性,表示状态0 1 2 3 4
            //change 改变
            xhr.onreadystatechange = function() {
                //判断服务端是否返回了所有的结果
                if (xhr.readyState === 4) {
                    //判断响应状态码 200 404 403 401 500
                    //2xx表示成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //响应行
                        //console.log(xhr.status); //状态码
                        //console.log(xhr.statusText); //状态字符串
                        //console.log(xhr.getAllResponseHeaders()); //所有响应头
                        //console.log(xhr.response); //响应体
                        result.innerHTML = xhr.response;
                    } else {

                    }
                }
            }
        }
    </script>
</body>
</html>
  • onreadystatechange()有四个值,分别对应readystate()函数的值从0-1、1-2、2-3、3-4
  • xhr.open('GET', 'http://127.0.0.1:8000/server');客户端发送get请求,服务器中路由也要设置get,app.get('/server', (request, response) => { ,如果客户端发送的是post请求,服务器端也要设置post

2.发送post请求

post.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Post</title>
   <style>
       #result {
           width: 200px;
           height: 100px;
           border: solid 1px #903;
       }
   </style>
</head>
<body>
   <div id="result"></div>
   <script>
       const result = document.getElementById('result');
       result.addEventListener('mouseover', function() {
         const xhr = new XMLHttpRequest();
         xhr.open('POST', 'http://127.0.0.1:8000/server');
         //设置请求头信息
         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
         
         xhr.send("a=100&b=200&c=300"); //发送参数的值
         xhr.onreadystatechange = function() {
             if (xhr.readyState === 4) {
                 if (xhr.status >= 200 && xhr.status < 300) {
                   result.innerHTML = xhr.response;
                 }
               } else {

               }
           }
       });
   </script>
</body>
</html>

3.服务端响应json数据

json.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON</title>
    <style>
    #result {
        width: 200px;
        height: 100px;
        border: solid 1px #89b;
    }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        const result = document.getElementById('result');
        window.onkeydown = function() {
            const xhr = new XMLHttpRequest();
            //设置响应体数据类型,自动转换数据
            xhr.responseType = 'json';
            xhr.open('GET', 'http://127.0.0.1:8000/json-server');
            xhr.send();
            xhr.onreadystatechange = function() {
              if (xhr.readyState === 4) {
                  if (xhr.status >= 200 && xhr.status < 300) {
                    //result.innerHTML = xhr.response;
                    //手动将response数据转化为对象
                    //let data = JSON.parse(xhr.response);
                    //console.log(data);
                    //result.innerHTML = data.name;
                    //自动对数据进行转换
                    console.log(xhr.response);
                    result.innerHTML = xhr.response.name;
                  }
                } else {

                }
            }
        }
    </script>
</body>
</html>
  • xhr.responseType = 'json'; 会自动将xhr.response转换成对象类型

4.服务器端

servser.js代码:

//引入express
const express = require('express');
//创建应用对象
const app = express();
//创建路由规则

//get请求
app.get('/server', (request, response) => {
    //设置响应头
  response.setHeader('Access-Control-Allow-Origin', '*');
  //设置响应体
  response.send('hello ajax GET');
});


//post请求
app.post('/server', (request, response) => {
  //设置响应头
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
response.send('hello ajax POST');
});


//服务端响应json数据
app.get('/json-server', (request, response) => {
  //设置响应头
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
const data = {
  name: 'jerry'
};
var str = JSON.stringify(data);
response.send(str);
});
//监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动,8000端口监听中....");
});
上一篇:前后端分离开发中处理跨域问题汇总


下一篇:Windows下启动Jmeter出现Not able to find Java executable or version问题解决方案