Ajax请求参数

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>

在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力做一只合格的前端攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值