XMLHttpRequest(异步的与服务器交换数据) 是 Ajax 的基础。
xhr 数据请求流程
- 跟昨天介绍的一样,首先是新建一个文件夹(我取的名字是LIANXI),在LIANXI文件夹里新建一个文件夹,名为public,在该文件夹里新建一个文件index.html. 在终端打开LIANXI文件夹,输入npm init ,一直按照默认值点击确认,完成后输入npm install express 安装需要的模块,最后在LIANXI文件夹里新建一个js 文件,名为index.js, 一会服务器上的代码将写在这里。

- 先写”客户端”,也就是index.html 中的文件
XMLHttpRequest 对象用于和服务器交换数据。这里发送数据请求的方式有两种,get和post
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用 然而,在以下情况中,请使用 POST 请求: 无法使用缓存文件(更新服务器上的文件或数据库) 向服务器发送大量数据(POST 没有数据量限制) 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
get 请求:
var xhr = new XMLHttpRequest() xhr.open('get','/getTest?name=fan&age=18',true); xhr.send();
post 请求,需要自己设置请求头
var xhr = new XMLHttpRequest() xhr.open('POST','/postTest',true) xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") xhr.send('num=1&des=我爱你')
在index.html 文件中,有两个button 按钮,分别使用get 和post 方法
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>xhr
title>
head> <body> <button onclick="get()">get方法
button> <button onclick="post()">post 方法
button> <script> function get() {
var xhr = new XMLHttpRequest() // open后面有三个参数: // 规定请求的类型、URL 以及是否异步处理请求。 // method:请求的类型;GET 或 POST // url:文件在服务器上的位置 // async:true(异步)或 false(同步) 默认为true xhr.open('get', '/getTest?name=fan&age=18') // 发送请求到后端(服务器) xhr.send() // 当请求被发送到服务器时,我们需要执行一些基于响应的任务。 // 每当 readyState 改变时,就会触发 onreadystatechange 事件。 // readyState 属性存有 XMLHttpRequest 的状态信息。 // 在xhr的准备状态发生改变的时候,调用该方法 xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText) } } } function post() {
var xhr = new XMLHttpRequest() // post 请求方式,接口后面不能追加参数 xhr.open('post', '/postTest') // 如果使用post 请求方式, 而且是以key=value 这种形式提交的 // 那么需要设置请求头的类型 xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded') xhr.send('num=1&des=我爱你') xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText) } } }
script>
body>
html>
- 写“服务端” 也就是index.js 中的内容
var express = require('express') var bodyParser = require('body-parser') var web = express() web.use(express.static('public')) // 设置对url 进行编码, 并且不允许url 进行扩展 // 如果设置为False, 那么参数只能为数组或者字符串 // 如果设置为TRUE, 那么参数为任意类型 web.use(bodyParser.urlencoded({extended:false})) web.get('/getTest', function(req, res){
var name1 = req.query.name var age = req.query.age console.log(name1) console.log(age) }) web.post('/postTest', function(req, res){
var num = req.body.num var des = req.body.des console.log(num) console.log(des) }) web.listen('8080', function(){
console.log('服务器启动了') })
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/221050.html原文链接:https://javaforall.net
