日期:2014-05-16  浏览次数:20847 次

ajax入门学习笔记

本文之于记录ajax技术的原理,不用框架及js库来实现数据的异步请求交互:

?

ajax是Asynchronous JavaScript and XML(即异步JavaScript和XML)一种融合多种技术的一种技术。好别扭(⊙o⊙)…

?

ajax的技术核心是XMLHttpRequest对象,对于XMLHttpRequest最早是在IE5.0中以ActiveX组件的形式出现的,后来Mozilla,chrome,Safari,Opera等浏览器厂商都支持了XMLHttpRequest,以及IE7+(IE7及以上版本)都支持了XMLHttpRequest对象,但IE5、IE5.5(这两个应该没人用了)、IE6(国内还是有N多人的机器上还是在用这个吧?!)还是用ActiveX对象来创建XMLHttpRequest对象,所以为了我们代码的鲁棒性,通用性,我们还是得照顾IE6及以下版本的浏览器,所以创建XMLHttpRequest对象需要对不同浏览器以不同方式来创建:

?

?

?

<script type="text/javascript">

var xmlhttp;

function loadXMLDoc(url){

xmlhttp=null;

if (window.XMLHttpRequest){

//针对IE7+,firefox,chrome,Safari,Opera等浏览器

? xmlhttp=new XMLHttpRequest();

? }else if (window.ActiveXObject){

? // 针对IE5 and IE6

? xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

if (xmlhttp!=null){

? xmlhttp.onreadystatechange=state_Change;//这里回调函数不能加括号,只写回调函数名

? xmlhttp.open("GET",url,true);//get方式发生http请求,第三个参数是表示异步提交?

? xmlhttp.send(null);

?

?

? ? ? ? ? ? ? ? //如果用post方式提交http请求

//xmlhttp.open("POST",url,true); 这里的url是不带请求参数的 参数在send里附带上

//xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//这句很重要 需要自己设置请求头信息

? ? ? ? ? ? ? ? //xmlhttp.send("param="+paramValue);

? }else{

? alert("您的浏览器不支持XMLHTTP,请升级您的浏览器.");

? }

}

?

function state_Change(){

if (xmlhttp.readyState==4){//readyState=4时表示服务器端的响应数据已经被全部接收

? if (xmlhttp.status==200){//status=200表示http连接状态正常

? ? // ...our code here...

var responseText = xmlhttp.responseText;//服务器响应的数据 文本形式

alert(responseText);

? ? }else{

? ? alert("Problem retrieving XML data");

? ? }

? }

}

</script>

?

?

XM