json response in ajax

Back to the general list of articles

json response in ajax

In actual work, we send a request to the server, and most of jsonthe data returned by the server is formatted data.
This article explains how to process jsonformatted data

The key used this time is the down arrow.
When you press the keyboard and press the down arrow button, the server returns the data

1. Create in testfive文件夹and in this folder
2. Create json.html文件
3. Createserver.js文件

Case number one

Make a
key used as the down arrow.
When you press the keyboard and press the down arrow button, the server returns the data
json.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="result" style="width: 300px;height: 200px;border: solid 2px teal;"></div>
    <script>
        // 一:获取元素对象
        const textone = document.getElementById('result');
        // 二:绑定键盘按下事件
        window.onkeydown = function(){
     
     
            // 测试打印
            console.log("已经按下按键");
            // 1.发送请求
            const textone = new XMLHttpRequest();
            // 2.初始化
            textone.open('GET','http://127.0.0.1:8000/jsonserver');
            // 3.发送
            textone.send();
            // 4.事件绑定
            textone.onreadystatechange = function(){
     
     
                if(textone.readyState === 4){
     
     
                    if(textone.status >= 200 && textone.status < 300){
     
     
                        // 测试打印
                        console.log(textone.response);
                        result.innerHTML = textone.response;
                    }
                }
            }
        }
    </script>
</body>
</html>

server.js文件

// 1. 引入express
const express = require('express');

// 2.创建对象
const app = express();

// 3.创建路由规则  里面的形参 request与response   (自己可以随便定义名字的)
//  建议写成  request与response  因为可以见名思意,方便自己看
// request  对请求报文的封装
// responst 对响应报文的封装
//  请求路径为'/server'

// 当使用post请求时候会因为发送的信息没有收到对应的结果所以回报错
// 所以该处使用all  表示可以接收任意类型的请求      如get post 等等
app.all('/jsonserver', (request, response)=>{
    
    
    // 设置响应头 设置允许跨域
    // 头名字为Access-Control-Allow-Origin
    // 头的值为
    response.setHeader('Access-Control-Allow-Origin','*');
    // 响应头        *号表示所有的头信息都可以接收
    response.setHeader('Access-Control-Allow-Headers','*');
    // 设置响应体
    response.send('ALL接收成功');

});

// 4. 监听端口启动服务
// 这里listen(8000)后面添加了一个回调,用来提示,告诉自己是否监听成功
app.listen(8000, ()=>{
    
    
    console.log("服务已经启动,8000端口监听中......");
});

Press the down arrow button to return to the data
Insert picture description here

Case two

Return this object to the browser in response to a piece of data

const data = {
    
    
    name: 'dalaojun'
};

This object directly to response.send()put inside is not enough, because send()there can only be put 字符串and butfer(这个忘记了淦)
so it is necessary to convert a string object
using the JSON.stringify()method of converting

server.js文件

// 1. 引入express
const express = require('express');

// 2.创建对象
const app = express();

// 3.创建路由规则  里面的形参 request与response   (自己可以随便定义名字的)
//  建议写成  request与response  因为可以见名思意,方便自己看
// request  对请求报文的封装
// responst 对响应报文的封装
//  请求路径为'/server'

// 当使用post请求时候会因为发送的信息没有收到对应的结果所以回报错
// 所以该处使用all  表示可以接收任意类型的请求      如get post 等等
app.all('/jsonserver', (request, response)=>{
    
    
    // 设置响应头 设置允许跨域
    // 头名字为Access-Control-Allow-Origin
    // 头的值为
    response.setHeader('Access-Control-Allow-Origin','*');
    // 响应头        *号表示所有的头信息都可以接收
    response.setHeader('Access-Control-Allow-Headers','*');
    // 响应一个数据   把这个对象返回给浏览器
    const data = {
    
    
        name: 'dalaojun'
    };
    // 对对象进行字符串转换
    let str = JSON.stringify(data);
    // 设置响应体
    response.send(str);

});

// 4. 监听端口启动服务
// 这里listen(8000)后面添加了一个回调,用来提示,告诉自己是否监听成功
app.listen(8000, ()=>{
    
    
    console.log("服务已经启动,8000端口监听中......");
});

Then what you get in the browser is the data that this object is converted into a string format
Insert picture description here

Case three

Convert the sent string data into objects in the front end

The result is a JSON format string
. It is relatively simple for us to obtain the results in simple data, but for complex data, it will be very troublesome to extract some of the data in it.

1. Manually perform a conversion on the data

// 手动对数据转化
let data = JSON.parse(textone.response);
// 在控制台中打印
console.log(data);
// 把name的值显示在方框内
result.innerHTML = data.name;

json.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="result" style="width: 300px;height: 200px;border: solid 2px teal;"></div>
    <script>
        // 一:获取元素对象
        const textone = document.getElementById('result');
        // 二:绑定键盘按下事件
        window.onkeydown = function(){
     
     
            // 测试打印
            console.log("已经按下按键");
            // 1.发送请求
            const textone = new XMLHttpRequest();
            // 2.初始化
            textone.open('GET','http://127.0.0.1:8000/jsonserver');
            // 3.发送
            textone.send();
            // 4.事件绑定
            textone.onreadystatechange = function(){
     
     
                if(textone.readyState === 4){
     
     
                    if(textone.status >= 200 && textone.status < 300){
     
     
                        // 测试打印
                        // console.log(textone.response);
                        // result.innerHTML = textone.response;
                        // 手动对数据转化
                        let data = JSON.parse(textone.response);
                        // 在控制台中打印
                        console.log(data);
                        // 把name的值显示在方框内
                        result.innerHTML = data.name;
                    }
                }
            }
        }
    </script>
</body>
</html>

The result is
Insert picture description here

2. Use automatic conversion

Modify above

// 自动转化
// 借助textone对象里面的属性来转化
// 设置响应体数据的类型
textone.responseType = 'json';

Edit below

//  使用自动转化
result.innerHTML = textone.response.name

json.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="result" style="width: 300px;height: 200px;border: solid 2px teal;"></div>
    <script>
        // 一:获取元素对象
        const textone = document.getElementById('result');
        // 二:绑定键盘按下事件
        window.onkeydown = function(){
     
     
            // 测试打印
            console.log("已经按下按键");
            // 1.发送请求
            const textone = new XMLHttpRequest();
            // 
            // 自动转化
            // 借助textone对象里面的属性来转化
            // 设置响应体数据的类型
            textone.responseType = 'json';
            // 2.初始化
            textone.open('GET','http://127.0.0.1:8000/jsonserver');
            // 3.发送
            textone.send();
            // 4.事件绑定
            textone.onreadystatechange = function(){
     
     
                if(textone.readyState === 4){
     
     
                    if(textone.status >= 200 && textone.status < 300){
     
     
                        // 测试打印
                        // console.log(textone.response);
                        // result.innerHTML = textone.response;
                        // 手动对数据转化
                        // let data = JSON.parse(textone.response);
                        // 在控制台中打印
                        // console.log(data);
                         // 把name的值显示在方框内
                        // result.innerHTML = data.name;
// 
                        // 测试打印
                        console.log(textone.response);
                        //  使用自动转化
                        result.innerHTML = textone.response.name;
                    }
                }
            }
        }
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_47021806/article/details/112057925