307 Ajax请求参数格式:json, x-www-form-urlencoded


补充:
(1)get请求的请求参数,以查询字符串的方式拼接在url后面;
(2)传统的表单提交,表单数据以查询字符串的方式传递给send()方法。

05.向服务器端传递JSON格式的请求参数.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">
        // 1.创建ajax对象
        var xhr = new XMLHttpRequest();
        // 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
        // 1)请求方式 2)请求地址
        xhr.open('post', 'http://localhost:3000/json');
        // 通过请求头告诉服务器端客户端向服务器端传递的请求参数的格式是什么
        xhr.setRequestHeader('Content-Type', 'application/json');
        // JSON.stringify() 将json对象转换为json字符串
        // 3.发送请求
        xhr.send(JSON.stringify({
            name: 'lisi',
            age: 50
        }));
        // 4.获取服务器端响应到客户端的数据
        xhr.onload = function() {
            console.log(xhr.responseText) // {"name":"lisi","age":50}
            console.log(typeof xhr.responseText) // string,responseText就是文本字符串
        }
    </script>
</body>

</html>

因为请求路径是json,所以在network里,看的时候,也是看name为json的。


原文地址:https://www.cnblogs.com/jianjie/p/12342849.html