js原生ajax发送get和post请求的实现


JS原生ajax的实现

创建一个node服务器(这里用了express框架)

// app.js

// 引入express框架
const express = require('express');
// 路径处理模块
const path = require('path');
const fs = require('fs');
// 创建web服务器
const app = express();

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 静态资源访问服务功能
app.use(express.static(path.join(__dirname, 'public_ajax')));

app.get('/api/get', (req, res) => {
	console.log(req.query)
	res.send(req.query)
})

app.post('/api/post', (req, res) => {
	console.log(req.body)
	res.send(req.body)
})

// 监听端口
app.listen(3000);
// 控制台提示输出
console.log('服务器启动成功');

这样就搭建了一个端口为3000的服务器.

原生ajax实现

public_ajax / ajax.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
<button onclick="sendAjax()">获取数据</button>
<script>
			const sendAjax = () => {
				let xhr = null

				//	判断浏览器是否支持XMLHttpRequest
				if (window.XMLHttpRequest) {
					// 对于 ie 6+的浏览器
					// 新建一个XMLHttpRequest实例对象
					xhr = new XMLHttpRequest()
				} else if (window.ActiveXObject) {
					// 对于 ie 5 ie 6 的浏览器
					// ActiveXObject
					xhr = new ActiveXObject("Microsoft.XMLHTTP")
				}

				if (xhr) {
				
// ---------------------  GET 请求  ------------------------------------
// open: ajax发送什么请求,以什么方式发送,是否异步
					// xhr.open("get", 'http://localhost:3000/api/get?username=sss&key=555',true)
//这是使用port请求方法的时候向服务器发送数据的方法,这里可以直接为空,也可以为null
					// xhr.send(null)
// ---------------------  POST 请求 参数格式 1  ------------------------------------
					xhr.open('post', "http://localhost:3000/api/post")
// 设置请求 json 参数格式的类型(POST请求必须要设置)
// 不设置的话会报错
					xhr.setRequestHeader('Content-Type', 'application/json')

					xhr.send(JSON.stringify({ "username": '154', "age": 15 }))
// ---------------------  POST 请求 参数格式 2 ------------------------------------
					xhr.open('post', "http://localhost:3000/api/post")

					xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					var params = 'username=' + 'aaa' + '&age=' + 15;
					xhr.send(params)

//------------------------------- 后续代码 ------------------------------------------
					xhr.onreadystatechange = dealChange
					function dealChange() {
						if (xhr.readyState === 4 && xhr.status === 200) {
							console.log(xhr.responseText)
						} else {
							console.log(xhr.readyState)
						}
					}
				} else {
					alert('您的浏览器不支持ajax')
				}
			}
		</script>
	</body>
</html>

知识点

  onreadystatechange :请求状态码发生改变的时候触发

  xhr.readyState :状态码

  xhr.responseText : 返回的数据

  xhr.status : HTTP状态码

  xhr.setRequestHeader : 设置请求头

关于状态码 :readyState

  0 :请求还没发生(open执行之前)
  1 :请求已经建立,还没发送(执行了open)
  2 :请求已经发送,正在处理(执行了send)
  3 :请求处理中,有一部分数据可以用,但还有没有完成的数据。
  4 :请求完全完成

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值