AJAX

2019-09-26  本文已影响0人  Bouc

Ajax | MDN

AJAX是异步的JavaScript和XML(Asynchronous JavaScript And XML)。简单点说,就是使用 XMLHttpRequest 对象与服务器通信。 它可以使用JSON,XML,HTML和text文本等格式发送和接收数据。AJAX最吸引人的就是它的“异步”特性,也就是说他可以在不重新刷新页面的情况下与服务器通信,交换数据,或更新页面。

创建一个简单的Ajax

if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function(){
    // Process the server response here.
};
httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send();

完整的例子

function ajax(url, cb) {
  let xhr;
  if(window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = ActiveXObject("Microsoft.XMLHTTP");
  }
  xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
      cb(xhr.responseText);
    } 
  }
  xhr.open('GET', url, true);
  xhr.send();
}

httpRequest.readyState的值

访问服务端返回的数据

GET 注意事项

POST 请求

POST请求则需要设置RequestHeader告诉后台传递内容的编码方式以及在send方法里传入对应的值

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type": "application/x-www-form-urlencoded");
xhr.send("key1=value1&key2=value2");

Ajax与cookie

withCredentials | MDN

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);
上一篇下一篇

猜你喜欢

热点阅读