设置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>Documenttitle>
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>
使用第三方模块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: ‘男’}”,如果有多个参数时需要使用“,”符号连接。
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>Documenttitle>
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>
创建服务器定义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>Documenttitle>
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>