AJAX 基本使用


1、创建 XMLHttpRequest 对象

    为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :

//
var xmlhttp = null ;
function createXmlhttp() {
 if(window.XmlhttpRequest) {
  xmlhttp = new XmlHttpRequest();
 }
 
 if(window.ActiveXObject) {
  try {
   xmlhttp = new ActiveXObject("microsoft.XMLHTTP") ;
  }catch(e) {
    xmlhttp = new ActiveXObject("msxml2.XMLHTTP");
  }
 
 }
 if(!xmlhttp) {
  alert("创建xmlhttp对象异常!");
        return false;
 }
}

 

2、向服务器发送请求

    如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:

xmlhttp.open("POST","ajax_test.action",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //向请求添加 HTTP 头
xmlhttp.send("fname=Bill&lname=Gates"); //请求的数据 

3、服务器两种响应方式 

    responseText获得字符串形式的响应数据。

    responseXML获得 XML 形式的响应数据。

4、onreadystatechange 事件

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

详细请参考

http://www.w3school.com.cn/ajax/index.asp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值