Ajax发送异步请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37508531/article/details/87110526

简介

  Ajax(Asynchronous JavaScript and XML)即异步的JS和XML,本质是使用JS提供的XMLHttpRequest对象异步地向服务器发送请求,并接受响应数据。服务器响应回来的是部分的数据而不是完整的页面,并且可以以无刷新的效果来更改页面中的局部内容。

获取Ajax核心对象:XMLHttpRequset

  允许通过 window.XMLHttpRequest来判断浏览器是否支持XMLHttpRequest()。如果值为null的话,说明需要通过ActiveXObject()创建。因此,产生了兼容的代码:

	var xhr;
	if(window.XMLHttpRequest){
		xhr=new XMLHttpRequest();
	}else{
		xhr=new ActiveXObject("Microsoft.XMLHTTP");
	}

xhr的常用属性和方法

  1.open() 方法,创建请求

  语法为:

open(method,url,isAsyn)

method:string类型;请求方式:get,post
url:string类型;请求地址
isAsyn:Boolean类型;指定采用同步(false)还是异步(true)的方式发送请求

  2.readyState属性

  当值为4的时候,表示所有的响应都已接收完毕

  3.status属性

  表示服务器的响应状态码。200表明成功响应所有信息

  4.onreadystatechange事件

  当 xhr 的 readyState 属性值发生改变的时候,要自动激发的操作

  语法为:

xhr.onreadystatechange = function(){

}

  5.send() 方法

  语法为:

send(body);

body是请求主体,没有请求主体的提交方式,body位置处写null

发送异步请求的步骤

  1.创建/获取xhr对象

	var xhr;
	if(window.XMLHttpRequest){
		xhr=new XMLHttpRequest();
	}else{
		xhr=new ActiveXObject("Microsoft.XMLHTTP");
	}

  2.创建请求

xhr.open("get","03-testajax.php",true);

  3.设置 xhr 的 onreadystatechange 事件,判断readyState 以及 status 的值,并接受响应

			xhr.onreadystatechange = function(){
					if(xhr.readyState==4 && xhr.status==200){
						//接收响应数据
						var resText = xhr.responseText;
						//对响应数据的处理
						$("msg-show").innerHTML = resText;
					}
				}

  4.发送请求

xhr.send(null);

猜你喜欢

转载自blog.csdn.net/m0_37508531/article/details/87110526
今日推荐