ajax

  1. 实例化XMLHttpRequest对象。
var xhr=null;
 try {
       xhr=new XMLHttpRequest();
  }catch (e){
        //ie6及其以下的版本
       xhr=new ActiveXObject('Microsoft.XMLHTTP');
       }
  1. 在使用xhr对象时,要使用的第一个方法是open().
xhr.open('get','1.example.txt',true);

这里接收三个参数,要发送请求的类型(get,post),请求的URL和是否异步(true:异步,false:同步)。
注意:这里并不会真正发送请求,而是启动一个请求以备发送

  1. 发送请求,调用send()方法。
xhr.send(null)

GET请求没有主体,所以应该传递null或者省略这个参数。POST请求通常拥有主体,同时它应该匹配使用setRequestHeader()指定的“Content-Type”头。

  1. get请求。
    get请求通常用于向服务器查询某些信息,必要时,可以将查询字符串参数追加到URL的末尾,但参数必须经过正确的编码。
function addURLParam(url,data) {
        url +='?';
        var arr = [];
        for(var name in data) {
            //   encodeURIComponent() :用于对 URI 中的某一部分进行编码
            arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
        }
        return url+arr.join('&');
    }

这里的data格式是json。
2.post请求。
对于请求,通常像服务器发送应该被保存的数据,应该把数据作为请求的主题提交,它不是以地址形式传参,而是在send()中传参。

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 
      // 传输数据  
      xhr.send(data);  

4.监听事件,只要 readyState 的值变化,就会调用 readystatechange 事件.。

xhr.onreadystatechange = function() {   
              //readyState值为4,说明所有数据已就绪 
        if ( xhr.readyState == 4 ) {
            if ( xhr.status == 200 && xhr.status<300 ) {
                alert(xhr.responseText)
            } else {
                alert('出错了,Err:' + xhr.status);
            }
        }   
    }

你可能感兴趣的:(ajax)