Ajax入门(五)
一、如何传递json定制开发小程序格式请求参数
1.1) json格式的Content-Type是:application/json
xhr.setRequestHeader('Content-Type', 'application/json');
- 1
传递的是,比如
{"name": "陈岳", "age": 32}
- 1
但是服务器需要的是字符串的文本,因此需要将成字符串格式的,比如
JSON.stringify({"name": "陈岳", "age": 32})
- 1
1.2) 在app.js使用use方法,并且创建路由
app.use(bodyParser.urlencoded());app.post('/post',(req, res) =>{ res.send(req.body);})
- 1
- 2
- 3
- 4
- 5
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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
1.4) 在浏览器运行
———————————————————————————————————————
上一篇:
下一篇: