js发送ajax请求

function initRequest()
{
    var request = false;
    if(window.XMLHttpRequest) {         //FireFox
    request = new XMLHttpRequest();
    if (request.overrideMimeType) {
      request.overrideMimeType('text/xml');
    }
  }
  else if (window.ActiveXObject) {    //IE
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
  if (!request) {
    window.alert("Create request error!");
    return false;
  }
  return request;
}

var http_request;
function send(sendUrl,sendData)
{
  http_request = initRequest();
  sendUrl += "&random="+Math.random();   //在URL后添加这个,可以保证不被缓存
  http_request.onreadystatechange = ajax_call_back;//指定请求返回时的回调函数
    
  //get
  http_request.open("GET", sendUrl,true);
  http_request.send(sendData);
  
  //post
  //http_request.open("POST", sendUrl, true);
  //http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  //http_request.send(sendData);
}

function ajax_call_back()
{
    //readyState共有5中状态,0未初始化,1已初始化,2发送请求,3开始接收结果,4接收结果完毕。
    //status服务器响应状态码
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
      var str = http_request.responseText;
      alert("返回数据为:"+str);
    }
    else if(http_request.status == 404){
      alert("请求资源不存在!");
    }
    else {
      alert("Ajax请求失败,错误状态为:"+http_request.status);
    }
  }
}

XMLHttpRequest 对象

 

属性

 

readyState

请求状态,开始请求时值为0直到请求完成这个值增长到4

responseText

目前为止接收到的响应体,readyState<3此属性为空字符串,=3为当前响应体,=4则为完整响应体

responseXML

服务器端相应,解析为xml并作为Document对象返回

status

服务器端返回的状态码,=200成功,=404表示“Not Found”

statusText

用名称表示的服务器端返回状态,对于“OK”为200,“Not Found”为400

方法

 

setRequestHeader()

向一个打开但是未发生的请求设置头信息

open()

初始化请求参数但是不发送

send()

发送Http请求

abort()

取消当前相应

getAllResponseHeaders()

把http相应头作为未解析的字符串返回

getResponseHeader()

返回http相应头的值

事件句柄

 

onreadystatechange

每次readyState改变时调用该事件句柄,但是当readyState=3有可能调用多次


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值