Ajax入门(五)

      • 一、如何传递json格式请求参数
        • 1.1) json格式的Content-Type是:application/json
        • 1.2) 在app.js使用use方法,并且创建路由
        • 1.3) 在public文件夹新建一个html文件
        • 1.4) 在浏览器运行

一、如何传递json格式请求参数

1.1) json格式的Content-Type是:application/json

xhr.setRequestHeader('Content-Type', 'application/json');

传递的是json对象,比如

{"name": "陈岳", "age": 32}

但是服务器需要的是字符串的文本,因此需要将json格式转换成字符串格式的,比如

JSON.stringify({"name": "陈岳", "age": 32})

1.2) 在app.js使用use方法,并且创建路由

app.use(bodyParser.urlencoded());

app.post('/post',(req, res) =>{
    res.send(req.body);
})

1.3) 在public文件夹新建一个html文件

<script>
        // 创建Ajax对象
        let xhr = new XMLHttpRequest();
        // 确定请求方法及路径,发送请求
        xhr.open('post', 'http://localhost:8822/json');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify({"name": "陈岳", "age": 32}));
        // 获取服务器传输的数据
        xhr.onload = function () {
            console.log(xhr.responseText);
        }
    </script>

1.4) 在浏览器运行


———————————————————————————————————————

上一篇:
Ajax学习日志(四)

下一篇:
Ajax学习日志(六)

更多推荐

Ajax学习日志(五)—— 如何传递json格式请求参数