1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 03-ajax传递get post请求参数

03-ajax传递get post请求参数

时间:2019-12-09 21:31:54

相关推荐

03-ajax传递get post请求参数

传递get请求参数

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><p><input type="text" id="username"></p><p><input type="text" id="age"></p><p><input type="button" value="提交" id="btn"></p><script type="text/javascript">// 获取按钮元素var btn = document.getElementById('btn');// 获取姓名文本框var username = document.getElementById('username');// 获取年龄文本框var age = document.getElementById('age');// 为按钮添加点击事件btn.onclick = function () {// 创建ajax对象var xhr = new XMLHttpRequest();// 获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;// 拼接请求参数var params = 'username='+ nameValue +'&age=' + ageValue;// 配置ajax对象xhr.open('get', 'http://localhost:3000/get?'+params);// 发送请求xhr.send();// 获取服务器端响应的数据xhr.onload = function () {console.log(xhr.responseText)}}</script></body></html>

app.js服务端

// 引入express框架const express = require('express');// 路径处理模块const path = require('path');const bodyParser = require('body-parser');const fs = require('fs');// 创建web服务器const app = express();app.get('/get', (req, res) => {res.send(req.query);});// 监听端口app.listen(3000);// 控制台提示输出console.log('服务器启动成功');

传递post请求参数

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><p><input type="text" id="username"></p><p><input type="text" id="age"></p><p><input type="button" value="提交" id="btn"></p><script type="text/javascript">// 获取按钮元素var btn = document.getElementById('btn');// 获取姓名文本框var username = document.getElementById('username');// 获取年龄文本框var age = document.getElementById('age');// 为按钮添加点击事件btn.onclick = function () {// 创建ajax对象var xhr = new XMLHttpRequest();// 获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;// 拼接请求参数var params = 'username='+ nameValue +'&age=' + ageValue;// 配置ajax对象xhr.open('post', 'http://localhost:3000/post');// 设置请求参数格式的类型(post请求必须要设置)xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');// 发送请求xhr.send(params);// 获取服务器端响应的数据xhr.onload = function () {console.log(xhr.responseText)}}</script></body></html>

app.js

// 引入express框架const express = require('express');// 路径处理模块const path = require('path');const bodyParser = require('body-parser');const fs = require('fs');// 创建web服务器const app = express();app.post('/post', (req, res) => {res.send(req.body);});// 监听端口app.listen(3000);// 控制台提示输出console.log('服务器启动成功');

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。