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文本文件中有汉字,则网页上显示的为乱码。
相关文章推荐
- (转载)Ajax初步认识
- 对Ajax的初步认识
- 初步认识ajax(个人整理)
- 初步认识ajax
- Ajax技术的初步认识一(转)
- Asp.net_Ajax局部刷新初步认识
- Asynchronous JavaScript and XML (AJAX) 的初步认识
- javascript DOM编程艺术学习笔记(3)Ajax初步认识:
- Ajax的初步认识
- Ajax初步认识
- Ajax的初步认识和封装
- ajax初步认识
- Ajax初步认识:
- CSS初步认识
- 数学建模的初步认识
- Struts 2与AJAX初步入门(1)
- 计算机操作系统初步认识几个常见问题
- 对EBS中配置文件的初步认识
- JavaScript 认识初步..
- Struts2拦截器初步认识