六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 29|回复: 0

Ajax XMLHttpRequest 异步请求

[复制链接]

升级  8%

16

主题

16

主题

16

主题

秀才

Rank: 2

积分
62
 楼主| 发表于 2013-1-29 10:34:26 | 显示全部楼层 |阅读模式
ajax异步请求即XMLHttpRequest请求:
兼容firefox,mozillar,safari,opera,IE等主流浏览器
以get请求为例子:

var xmlHttp;
var bgArgument;
var responseFunction;
/**
* url:request path
* argName: argument name
* argName: argument value
*/
function httpRequest(url,argName,argValue){
    if(window.XMLHttpRequest){
             //support firfox, mozillar,safari,opera,IE7 later version
try{
xmlHttp = new XMLHttpRequest();
//mozillar bug
if(xmlHttp.overrideMimeType){
xmlHttp.overrideMimeType("text/xml");
}
}catch(e){
    alert('do not support '+e);
}
    }else if(window.ActiveXObject){
        //support IE6 previous version
        var activexName = ["Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
        for(var i=0; i<activexName.length; i++){
            try{
              xmlHttp = new ActiveXObject(activexName[i]);
              break;
            }catch(e){
             alert('do not support IE '+e);
            }
        }
    }
    if(!xmlHttp){
        alert('create XMLHttpRequest failed');
        return;
    }

    //regist callback function
    xmlHttp.onreadystatechange = callback;
    xmlHttp.open("GET",url+"?"+argName+"="+argValue,true);
    xmlHttp.send(null);
   
   
}

//callback
function callback(){
     //request server success
     if(xmlHttp.readyState == 4){
         //response success
         if(xmlHttp.status == 200){
              var result = xmlHttp.responseText;
              //handler response result
         }else{
             alert("response failed");
         }
     }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表