前言:
本文为javascript中ajax使用的快速指南,旨在作为一个快速上手使用的资料备份,更长使用的为jQuery中封装后的ajax技术。
一、获取XMLHttpRequest对象
ajax的核心为XMLHttpRequest对象,通过该对象和服务器进行异步交互,因此使用Ajax技术的第一步,就是从不同的浏览器获取该对象的实例。
获取xhr对象的代码(附注:该段代码源自w3cschool):
function getXmlHttpRequest() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
二、发送异步请求
常用的web请求方式有两种,即get和post,得到xhr对象之后,通过这两种请求方式可以和服务器进行异步交互。
get方式:get方式与服务器进行交互,无需显示传递参数,传递的参数附在url末尾,因此获取xhr对象之后,send方法传入的参数为null;
post方式:post方式与服务器进行交互,请求参数封装在请求体中,因此需要通过xhr的send方法显示传递参数,另外,post方式交互原理是通过xhr模拟post方式提交表单,因此必须显示的设置请求头参数"content-type"为"application/x-www-form-urlencoded",否则服务器不能正常解析请求(具体原因,请参考HTTP协议);
javascript实现的代码如下:
window.onload = function(){
var xhr = getXmlHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4)
if(xhr.status == 200){
alert("数据已经成功发送到服务器");
alert(xhr.statusText);
}
};
//get方式
document.getElementById("getBtn").onclick = function(){
xhr.open("get", "/ajax_demo/info?username=zhangsan&password=123");
xhr.send(null);
};
//post方式
document.getElementById("postBtn").onclick = function(){
xhr.open("post", "/ajax_demo/info");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
//post方式发送参请求参数
xhr.send("username=lisi&password=456");
};
document.getElementById("showProductInfo").onclick = function(){
xhr.open("post", "/ajax_demo/product");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
//post方式,如果无参,则传null
xhr.send(null);
};
};
附注:
本文如有错漏,烦请联系,不胜感激!