您的位置:首页 > 其它

AJAX初步认识

2010-09-17 21:20 357 查看
]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script type="text/javascript"><!--
var xmlReq=null;
var console1=null;
//取得XmlHttpRequest对象
function getXmlHttpRequest(){
if(window.XMLHttpRequest){
xmlReq=new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xmlReq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
try{
xmlReq=new ActiveXOjbect("Msxml2.XMLHTTP");
}catch(e){
try{
xmlReq=new ActiveXOjbect("Msxml3.XMLHTTP");
}catch(e){}
}
}
}
if(!xmlReq){
alert("创建XmlHttpRequest失败!");
return false;
}
}
//发送请求
function sendRequest(url,httpmethod,params){
if(!httpmethod){
httpmethod="GET";
}
getXmlHttpRequest();//获得XmlHttpRequest对象
if(xmlReq){
xmlReq.onreadystatechange=callback;
xmlReq.open(httpmethod,url,true);
xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlReq.send(params);
}
}
//回调函数
function callback(){
var data=null;
if(xmlReq.readyState==4){
if(xmlReq.status==200){
data=xmlReq.responseText;
toConsole(data);
}
}
}
//将服务器返回的信息显示到页面之中。
function toConsole(data){
if(console1){
var text=document.createTextNode(data);
console1.appendChild(text);
}
}
//当页面加载完毕后调用
window.onload=function(){
console1=document.getElementById("console");
sendRequest("question.txt",null,null);
}
// --></mce:script>
</head>

<body>
<div id="console"></div>
</body>
</html>


本段代码对AJAX进行初步认识:

若想与服务器进行交互则一般有以下几步:

1.创建XMLHttpRequest对象。

2.注册回调函数。xmlReq.onreadystatechange=callback;

3.向服务器提出申请:xmlReq.open(param1,param2,param3);//第一个函数为向服务器申请方式通常有"GET"和"POST".

4.向服务器发送数据:xmlReq.send(data);//若为"GET"方式,则data为null.

5.编写回调函数(callback)的具体行为。

但是有一点缺憾:若question.txt文本文件中有汉字,则网页上显示的为乱码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: