Ajax

基本概念

Asynchronous JavaScript and XML, 所用到的技术有DHTML、JavaScript、DOM和HTML。

  • XMLHttpRequest对象
var xhr = new XMLHttpRequest();//创建一个新实例
  • open方法
xhr.open("get", "url?dataName1=" + encodeURIComponent(value1) + "&dataName2=" + encodeURIComponent(value2), true);

open方法可以接收三个参数,第一个是表示要发送的请求类型(可以是get或post),第二个是请求的URL(和后台函数对接的凭据,如果是get方法,传送的数据跟在URL后),第三个是表示是否异步发送请求的布尔值。

  • send方法
xhr.open("post", url, true);
//...
var str = "hello, world!";
xhr.setRequestHeader("Content-Type", "text/plain");
send(str);

当要发送的请求类型为post时,send方法接收一个参数,即要作为请求主体发送的数据;当要发送的请求类型为get时,send不接收参数或接收null。使用post方法时,需要在open()后send()前,调用setRequestHeader()方法,设置Content-Type

基础举例
function exampale() {
    var xhr = new XMLHttpRequest(); //XMLHttpRequest
    xhr.open("get", "url?dataName1=" + encodeURIComponent(value1) + "&dataName2" + encodeURIComponent(value2), true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            //code
        }
    }
    send();
}