Ajax请求参数
- GET请求参数的传递
- 创建服务器
- 通过表单访问服务器
- POST请求参数的传递
- application/x-www-form-urlencoded参数的接收与发送
- 创建服务器
- 通过表单访问服务器
- JSON格式数据的发送与接收
- 创建服务器
- 通过表单访问服务器
GET请求参数的传递
设置open()方法中的第1个参数为“get”,表示设置get请求方式。
xhr.open('get', 'http://localhost:3000/demo.html?username=zhangsan &age=20');
xhr.send();
“?”后面的“username=zhangsan&age=20”表示GET请求参数,
多个参数时需要使用“&”符号连接。
创建服务器
创建服务器将客户端请求的数据给发送出去。
const express = require('express');
const path = require('path');
const app = express();
app.all('*', function(req, res, next) {//处理跨域问题res.header("Access-Control-Allow-Origin", "*");res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header('Access-Control-Allow-Headers',['mytoken','Content-Type'])next();});
app.use(express.static(path.join(__dirname, 'public')));
// 定义GET路由
app.get('/get', (req, res) => {res.send(req.query);
});
app.listen(3000);
console.log('服务器启动成功');
通过表单访问服务器
创建一个网页,然后通过一个表单来提交数据,再将服务器发送来的数据接收并在控制台打印出来。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><form action="#" method="" style="width: 245px;">用户名:<input type="text" id="username" style="float: right;" /><br><br>年龄:<input type="text" id="age" style="float:right;" /><br><br><input type="button" value="提交" id="btn" /><br><br></form><script>// 获取姓名文本框var username = document.getElementById('username');// 获取年龄文本框var age = document.getElementById('age');// 获取按钮元素var btn = document.getElementById('btn');// 为按钮添加单击事件btn.onclick = function () {// 获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;// 为按钮添加单击事件btn.onclick = function () {var xhr = new XMLHttpRequest();// 拼接请求参数var params = 'username=' + nameValue + '&age=' + ageValue;xhr.open('get', 'http://localhost:3000/get?' + params);xhr.onload = function () { console.log(JSON.parse(xhr.responseText)); };xhr.send();};};</script></body></html>
结果如下
POST请求参数的传递
使用第三方模块body-parser来处理POST请求参数
在server目录,下载body-parser模块,执行命令如下。
npm install body-parser@1.18.3 --save
请求消息是在HTTP请求和响应的过程中传递的数据块。
Ajax对象中的setRequestHeader()方法用来设置请求消息中请求头信息。
基本语法格式:
xhr.setRequestHeader('Content-Type', '请求参数格式');
xhr.send(请求参数);
Content-Type是属性名称;第2个参数是请求参数的格式。
实例:
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
application/x-www-form-urlencoded请求参数的格式是用“&”符号连接多个“参数名称等于参数值”形式的数据。
如“name=zhangsan&age=20&sex=nan”。
xhr.setRequestHeader('Content-Type', 'application/json');
application/json请求参数的格式是JSON数据。
如“{name: ‘张三’, age: ‘20’, sex: ‘男’}”,如果有多个参数时需要使用“,”符号连接。
application/x-www-form-urlencoded参数的接收与发送
创建服务器
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
app.all('*', function (req, res, next) {//处理跨域问题res.header("Access-Control-Allow-Origin", "*");res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header('Access-Control-Allow-Headers', ['mytoken', 'Content-Type'])next();});
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));// 定义POST路由
app.post('/post', (req, res) => {res.send(req.body);
});
app.listen(3000);
console.log('服务器启动成功');
通过表单访问服务器
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><form action="#" method="" style="width: 245px;">用户名:<input type="text" id="username" style="float: right;" /><br><br>年龄:<input type="text" id="age" style="float:right;" /><br><br><input type="button" value="提交" id="btn" /><br><br></form><script>// 为按钮添加单击事件btn.onclick = function () {// 获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;// 拼接请求参数var params = 'username=' + nameValue + '&age=' + ageValue;var xhr = new XMLHttpRequest();xhr.open('post', 'http://localhost:3000/post');// 设置请求参数格式的类型xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');// 获取服务器端响应的数据xhr.onload = function () {console.log(JSON.parse(xhr.responseText));};// 发送请求时,传入请求参数xhr.send(params);};</script></body></html>
JSON格式数据的发送与接收
创建服务器
创建服务器定义post路由,接收JSON格式数据,将客户端的数据发送出去。
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
app.all('*', function (req, res, next) {//处理跨域问题res.header("Access-Control-Allow-Origin", "*");res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header('Access-Control-Allow-Headers', ['mytoken', 'Content-Type'])next();});
app.use(express.static(path.join(__dirname, 'public')));
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());// 定义POST路由
app.post('/post', (req, res) => {res.send(req.body);
});
app.listen(3000);
console.log('服务器启动成功');
通过表单访问服务器
发送JSON格式数据
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><form action="#" method="" style="width: 245px;">用户名:<input type="text" id="username" style="float: right;" /><br><br>年龄:<input type="text" id="age" style="float:right;" /><br><br><input type="button" value="提交" id="btn" /><br><br></form><script>// 获取姓名文本框var username = document.getElementById('username');// 获取年龄文本框var age = document.getElementById('age');// 获取按钮元素var btn = document.getElementById('btn');// 为按钮添加单击事件btn.onclick = function () {var xhr = new XMLHttpRequest();// 获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;// 定义params对象var params = {};params['username'] = nameValue;params['age'] = ageValue;xhr.open('post', 'http://localhost:3000/post');// 设置请求参数格式的类型xhr.setRequestHeader('Content-Type', 'application/json');// 获取服务器端响应的数据xhr.onload = function () {console.log(JSON.parse(xhr.responseText));};// 发送请求时,传入请求参数xhr.send(JSON.stringify(params));};</script></body></html>