前端路线--Ajax(day02)

本文详细介绍了两种常见的Ajax请求方式——GET和POST。对于GET请求,展示了如何创建XMLHttpRequest对象、设置监听事件、打开请求并发送数据,以及处理响应。而对于POST请求,不仅包括了相同的操作步骤,还特别强调了需要设置请求头以发送键值对数据。通过实例代码,阐述了GET和POST在实际应用中的不同。
摘要由CSDN通过智能技术生成

Ajax请求–get

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<p><input type="text"></p>
		<button>get请求</button>
		<div class="box"></div>
	</body>
	<script type="text/javascript">
		var btn=document.querySelector('button');
		var box=document.querySelector('.box');
		
		btn.addEventListener('click',function () {
			//1.创建XMLHttpRequest对象
			var xhr=new XMLHttpRequest();
			//2.设置状态改变的监听事件
			xhr.onreadystatechange=function () {
				//5.判断状态为4并且相应状态码为200
				console.log(xhr.readyState,xhr.status);
				if(xhr.readyState==4 && xhr.status==200){
					//6.获取结果进行处理和渲染
					box.innerText=xhr.responseText;//响应主体正文
					console.log(xhr.responseText);//响应主体
					console.log(JSON.parse(xhr.responseText));
				}
			}
			//3.打开请求,设置请求方式和url:
			xhr.open("GET","http://localhost:3008/api/student/getStudent ");
			//4.发送请求
			xhr.send();
		
		})
			
			
			
		/* 
			//返回准备的状态
			xhr.readyState 
			0:初始化,尚未调用open()方法
			1:启动,已调用open()方法,但尚未调用send()方法
			2:发送,已调用send()方法,接收到响应头信息
			3:接收,已经接收到部分响应主体
			4:完成,已经接收到全部响应数据,而且已经可以在客户端使用了
			
			//返回状态码
			xhr.status
			200为正常
			
			//返回响应主体正文
			.respnseText
			.response			//响应主体
			
		 */	
	</script>
</html>

Ajax请求–post

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<p><input type="text"></p>
		<button>get请求</button>
		<div class="box"></div>
	</body>
	<script type="text/javascript">
		var btn=document.querySelector('button');
		var box=document.querySelector('.box');
		
		btn.addEventListener('click',function () {
			//1.创建XMLHttpRequest对象
			var xhr=new XMLHttpRequest();
			//2.设置状态改变的监听事件
			xhr.onreadystatechange=function () {
				//5.判断状态为4并且相应状态码为200
				if(xhr.readyState==4 && xhr.status==200){
					//6.获取结果进行处理和渲染
					console.log(xhr.responseText);
					box.innerText=xhr.responseText;//响应主体正文
				}
			}
			//3.打开请求,设置请求方式和url:
			xhr.open("POST","http://localhost:3008/api/student/addStudent ");
			//4.设置请求头:请求数据能为键值对:k=v&k=v&k=v
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			//5.发送数据,send()里面填写键值对形式
			xhr.send("clazz=虎墩墩&name=小谷&gender=男&age=10&tel=1001&hobby=LOL&address=郑州&remark=其他 ");
		
		})
			
			
			/* 
			post请求必须在发送前设置请求头
			
			//用来告诉服务端主体是序列化后的 JSON 格式的字符串
			xhr.setRequestHeader("Content-Type","application/json"); 

		//完整的判断
			if(xhr.readystate==4){
				if(xhr.status==304||xhr.status==304>=200&&xhr.status<300){
					
				}
			}

			 */
	</script>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值