XMLHttpRequest的简单实例

  • 格式:pdf
  • 大小:58.11 KB
  • 文档页数:2

XMLHttpRequest的简单实例

刚学习了XMLHttpRequest这个类以及⼀些简单的应⽤,写⼀篇博客分享给⼤家也加深⾃⼰对ajax⼊门知识的体会。

ajax.js⽂件内容如下:

//定义xmlhttp作为XMLHttpRequest或者ActiveXObject类的句柄

var xmlhttp;

//初始化xmlhttp,根据浏览器的类型来判断选择哪个类来进⾏

function InitialXMLHttpRequest()

{

if(window.ActiveXObject)

{

xmlhttp=new ActiveXObject("window.Microsoft");//若为微软的浏览器则选择这种初始化⽅式

}

else if(window.XMLHttpRequest)

{

xmlhttp=new XMLHttpRequest();

}

else

{

alert("The browser is not compatible!");

}

}

//按照我个⼈理解这个函数是⽤于完成获取url资源的初始化⼯作

function getInfo(url)

{

//创建⼀个新的http请求,并指定此请求的⽅法、URL以及验证信。

xmlhttp.open("get","for.php?id="+url);

//执⾏showinfo函数

xmlhttp.onreadystatechange=showinfo;

xmlhttp.send(null);

}

//获取getinfo函数初始化的url资源,并将其在info对应的div中显⽰。

function showinfo()

{

var info = xmlhttp.responseText;

document.getElementById("info").innserHTML=info;

}

//ajax.html代码如下//⼊⼝页⾯代码,onclick出发启动getInfo('...');div⽤于创建⼀个盒⼦容纳showinfo中info的内容;