原生Ajax请求流程:同步请求、异步请求

  • Ajax
    • 异步无刷新技术
    • 原生Ajax的实现流程
      • 得到XMLHttpRequest对象
        - var xhr = new XMLHttpRequest();
      • 打开请求
        - xhr.open(method,url,async);
        - method:请求方式,通常是GET|POST
        - url:请求地址
        - async:是否异步。如果是true,表示异步,false表示同步
      • 发送请求
        - xhr.send(params);
        - params:请求时需要传递的参数
        - 如果是GET请求,设置null(GET请求设置在url后面)
        - 如果是POST请求,无参数设置为null,有参数则设置参数
      • 接受响应
        - xhr.status xiangy状态(状态码)
        - xhr.responseText 得到响应结束
  • 同步请求
<script type="text/javascript">
			/**
			 * 同步请求
			 */
			function test01() {
				//得到XMLHttpRequest对象
				var xhr = new XMLHttpRequest();
				
				console.log(xhr.readyState);//准备状态
				//打开请求
				xhr.open('GET','js/data.json',false); //同步请求
				
				console.log(xhr.readyState);//准备状态
				// 发送请求
				xhr.send(null);
				
				console.log(xhr.readyState);//准备状态
				// 判断响应状态
				if(xhr.status == 200){
					console.log(xhr.readyState);//准备状态
					// 获取响应结果
					console.log(xhr.responseText);
				}else{
					console.log("状态码:"+xhr.status+",原因:"+xhr.responseText);
				}
				
				console.log("同步请求。。。。");
			}
			
			// 同步请求
			test01();
		</script>
  • 异步请求
<script type="text/javascript">
			/**
			 * 异步请求
			 */
			function test02(){
				//得到XMLHttpRequest对象
				var xhr = new XMLHttpRequest();
			
				// console.log(xhr.readyState);//准备状态
				//打开请求
				xhr.open('GET','js/data.json',true); //异步请求
				
				// console.log(xhr.readyState);//准备状态
				// 发送请求
				xhr.send(null);
				
				/**
				 * 由于是异步请求,所以需要知道后台已经将请求处理完毕,才能获取响应结果
				 * 通过监听readyState的变化来得知后面的处理状态(4表示完全处理成功)
				 *	xhr.onreadystatechange = function(){
						
				 *  }
				 */
				xhr.onreadystatechange = function(){
					// 当readySate的值为4时,表示结果成功响应
					if( xhr.readyState == 4){
						// 判断响应状态
						if(xhr.status == 200){
							// console.log(xhr.readyState);//准备状态
							// 获取响应结果
							console.log(xhr.responseText);
						}else{
							console.log("状态码:"+xhr.status+",原因:"+xhr.responseText);
						}
					} 
				}
				
				// console.log(xhr.readyState);//准备状态
				console.log("异步请求。。。。");
			}
			
			// 异步请求
			test02();
		</script>

版权声明:本文为m0_51258512原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。