ajax基础知识

本文详细介绍了Ajax的基础知识,包括基本语法、处理JSON数据、GET和POST请求参数的传递,特别是如何发送JSON格式的POST请求。同时,还讨论了在低版本浏览器中获取响应数据的方法、Ajax错误处理及缓存利用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.基本语法

<script type="text/javascript">
		// 1.创建ajax对象
		var xhr = new XMLHttpRequest();
		// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
		// 1)请求方式 2)请求地址
		xhr.open('get', 'http://localhost:3000/first');
		// 3.发送请求
		xhr.send();
		// 4.获取服务器端响应到客户端的数据
		xhr.onload = function (){
			console.log(xhr.responseText)
		}
	</script>

2.处理服务器端返回的JSON数据

<script type="text/javascript">
		// 1.创建ajax对象
		var xhr = new XMLHttpRequest();
		// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
		// 1)请求方式 2)请求地址
		xhr.open('get', 'http://localhost:3000/responseData');
		// 3.发送请求
		xhr.send();
		// 4.获取服务器端响应到客户端的数据
		xhr.onload = function (){
			// console.log(typeof xhr.responseText) String
			// 将JSON字符串转换为JSON对象 `因为服务器传过来的为字符串类型`
			var responseText = JSON.parse(xhr.responseText);
			// 测试:在控制台输出处理结果
			console.log(responseText)
			// 将数据和html字符串进行拼接
			var str = '<h2>'+ responseText.name +'</h2>';
			// 将拼接的结果追加到页面中
			document.body.innerHTML = str;
		}
	</script>

3.传递get请求参数

		<input type="text" id="username"><input type="text" id="age">
		<input type="button" value="提交" id="btn">
	<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)
			}
		}

4.传递post请求参数

<input type="text" id="username"><input type="text" id="age">
<input type="button" value="提交" id="btn">
<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');
			//json格式传递见下面5
			// 发送请求
			xhr.send(params);
			// 获取服务器端响应的数据
			xhr.onload = function () {
				console.log(xhr.responseText)
			}
		}
	</script>

5.向服务器端传递JSON格式的请求参数(这个必须为post请求)

<script type="text/javascript">
		// 1.创建ajax对象
		var xhr = new XMLHttpRequest();
		// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
		// 1)请求方式 2)请求地址
		xhr.open('post', 'http://localhost:3000/json');
		// 通过请求头告诉服务器端客户端向服务器端传递的请求参数的格式是什么
		xhr.setRequestHeader('Content-Type', 'application/json');
		// JSON.stringify() 将json对象转换为json字符串
		// 3.发送请求
		xhr.send(JSON.stringify({name: 'lisi', age:50}));
		// 4.获取服务器端响应到客户端的数据
		xhr.onload = function (){
			console.log(xhr.responseText)
		}
	</script>

6.获取服务器端响应数据的另一种方式(适用低版本浏览器如IE)

<script type="text/javascript">
		var xhr = new XMLHttpRequest();
		// 0 已经创建了ajax对象 但是还没有对ajax对象进行配置
		console.log(xhr.readyState);
		xhr.open('get', 'http://localhost:3000/readystate');
		// 1 已经对ajax对象进行配置 但是还没有发送请求
		console.log(xhr.readyState);

		// 当ajax状态码发生变化的时候出发
		xhr.onreadystatechange = function() {
			// 2 请求已经发送了
			// 3 已经接收到服务器端的部分数据了
			// 4 服务器端的响应数据已经接收完成
			console.log(xhr.readyState);
			// 对ajax状态码进行判断 如果状态码的值为4就代表数据已经接收完成了
			if (xhr.readyState == 4) {
				console.log(xhr.responseText);
			}
		} 

		xhr.send();

7.Ajax错误处理(响应状态码和网络连接中断)

<button id="btn">发送Ajax请求</button>
	<script type="text/javascript">
		var btn = document.getElementById('btn');

		btn.onclick = function () {
			// 1.创建ajax对象
			var xhr = new XMLHttpRequest();
			// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
			// 1)请求方式 2)请求地址
			xhr.open('get', 'http://localhost:3000/error');
			// 3.发送请求
			xhr.send();
			// 4.获取服务器端响应到客户端的数据
			xhr.onload = function (){
				// xhr.status 获取http状态码
				console.log(xhr.responseText);
				if (xhr.status == 400) {
					alert('请求出错')
				}
			}
			// 当网络中断时会触发onerrr事件
			xhr.onerror = function () {
				alert('网络中断, 无法发送Ajax请求')
			}
		}
		// Ajax状态码: 表示Ajax请求的过程状态 ajax对象返回的
		// Http状态码: 表示请求的处理结果 是服务器端返回的
	</script>

8.Ajax缓存(读取文件)

<button id="btn">发送Ajax请求</button>
	<script type="text/javascript">
		var btn = document.getElementById('btn');
		btn.onclick = function () {
			// 1.创建ajax对象
			var xhr = new XMLHttpRequest();
			// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
			// 1)请求方式 2)请求地址
			xhr.open('get', 'http://localhost:3000/cache?t=' + Math.random());
			// 3.发送请求
			xhr.send();
			// 4.获取服务器端响应到客户端的数据
			xhr.onreadystatechange = function (){
				if (xhr.readyState == 4 && xhr.status == 200) {
					alert(xhr.responseText);
				}
			}
		}
	</script>

以上文件路由代码

// 引入express框架
const express = require('express');
// 路径处理模块
const path = require('path');
const bodyParser = require('body-parser');
const fs = require('fs');//读取文件文件
// 创建web服务器
const app = express();
// app.use(bodyParser.urlencoded());//Post请求需要转换的方法必写不然获取不到
app.use(bodyParser.json());//获取json数据需要写的方法

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

// 对应1
app.get('/first', (req, res) => {
    res.send('Hello, Ajax');
});
// 对应2
app.get('/responseData', (req, res) => {
    res.send({ "name": "zs" });
});
// 对应3
app.get('/get', (req, res) => {
    res.send(req.query);
});

// 对应4
app.post('/post', (req, res) => {
    res.send(req.body);
});

// 对应5
app.post('/json', (req, res) => {
    res.send(req.body);
});

// 对应6
app.get('/readystate', (req, res) => {
    res.send('hello');
});

// 对应7
app.get('/error', (req, res) => {
    //console.log(abc);
    res.status(400).send('not ok');
});

// 对应8
app.get('/cache', (req, res) => {
    fs.readFile('./test.txt', (err, result) => {
        res.send(result);
    });
});
// 监听端口
app.listen(3000);
// 控制台提示输出
console.log('服务器启动成功');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值