Ajax的使用体验
时间:2010-09-11 来源:hlhcto
Ajax其实很简单,我现在就将用Ajax技术开发时用的方法和步聚分享给大家
- //一、创建xmlhttp对象
- function createXMLHttpRequest()
- {
- if(window.ActiveXObject){
- //MS IE
- try{
- xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
- }catch(e){
- try{
- xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
- }catch(e){ }
- }
- }else if(window.XMLHttpRequest){
- //NOT MS IE
- xmlhttp=new XMLHttpRequest();
- }
- if(!xmlhttp){
- xmlhttp=false;
- alert("无法建立 Ajax 请求对象,你的浏览器版本太低,建议升级你的浏览器.");
- //window.location.href="ajaxError.htm";
- }
- //二、写一个公共的调用函数
- var pubdiv="";
- function AjaxGetContent(url,divobj)
- {
- pubdiv=divobj;
- createXMLHttpRequest();
- document.getElementById(divobj).innerHTML="正在载入...";
- xmlhttp.onreadystatechange=ResultAjaxGetContent; //ajax回调函数
- xmlhttp.open("post",url,true);
- xmlhttp.send(null)
- }
- //ajax回调函数
- function ResultAjaxGetContent()
- {
- if (xmlhttp.readyState==4)
- {
- if (xmlhttp.status==200)
- {
- document.getElementById(pubdiv).innerHTML=xmlhttp.responseText;
- }
- }
- }
- //三、写具体的事件功能函数,调用上面定义的ajax公用函数实现具体功能
- 如
- //div_car:为页面上要显示购物车信息的图层ID
- function AjaxShowCart()
- {
- var url="cart.asp?userid=8";
- AjaxGetContent(url,"div_cart")
- }
- //通过以上三步就可使用AJAX功能了!现在有很多的ajax框架可用,但个人觉得在很多的时候那些显得有些庞大的框架根本就用不着,自己写的代码更实用又方便!
相关阅读 更多 +