ajax的基本使用

1.什么是ajax?

ajax(异步 javaScript xml)能够刷新网页局部数据而不是刷新网页。

2.如何使用ajax?

第一步,创建xmlHttpRequest对象 var xmlHttpRequest = new XmlHttpRequest();

var xhttp;
		if (window.XMLHttpRequest) {
			//现代主流浏览器
			xhttp = new XMLHttpRequest();
		} else {
			// 针对浏览器,比如IE5或IE6
			xhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

第二步,xmlHttpRequest对象的open()和send()方法发送给服务器

xhttp.open("get", "${pageContext.request.contextPath}/emps", true);
          
 xhttp.send();

open()方法中的几个参数分别是open(method,url,async)

method 是ajax的请求类型 get或者post请求

url 是请求的url 统一资源标识符

async是是否同步或者异步 true 或者 false

send()方法 发送出请求

第三步,使用xmlhttprequest对象的responseText或responseXML属性获得服务器的响应

document.getElementById("demo").innerHTML = xhttp.responseXML;

第四步,onreadystatechange是从 0 到4,0表示请求未被初始化 1表示服务器连接成功 2表示请求被服务器接收 3表示处理请求 4表示请求处理完成 并且准备响应

readyState属性有多个状态码 就是请求状态码 200表示请求完成 

xhttp.status == 200 && xhttp.onreadystatechange==4  

这是传统的js的ajax写法,现在在jquery中ajax的写法为这样的

 在JQuery中的写法应该为这样的

$.ajax({
    type: "",
    url: "",
    data: $('#someForm').serizlize(),
    success: function ( data ) {}
    timeout: 15000,
    error: function ( data ) {}
})

 由于JQuery中队JavaScript进行了大量底层封装,所以这个封装的思路是

了解内部常见参数

type :是请求的方法 常见的有get 和post请求

url:请求的路径

data:请求传递的数据 这个地方使用了form表单数据序列化 

success:请求成功调用什么方法 

timeout设置超时时间

error:请求失败调用什么方法

这里是我自己写的ajax的jaquery版本使用

$.ajax({
			url : "${pageContext.request.contextPath}/emps",
			data : "pn=" + pn,
			type : "get",
			async : true,
			success : function(result) {
				console.log(result);
				//1.解析员工数据
				build_emps_tables(result);
				//2.解析并显示分页信息
				build_page_info(result);

				build_page_nav(result);
			}
		});

  

原文地址:https://www.cnblogs.com/ad-zhou/p/9857016.html