Ajax, 是使用XMLHttpRequest对象与服务器进行通讯。它能够发送和接收各类格式的信息,包括JSON,XML,HTML和文本文件。它有如下两个功能:浏览器
if (window.XMLHttpRequest) { // 新浏览器... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // 旧浏览器 httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
httpRequest.onreadystatechange = nameOfTheFunction;
httpRequest.onreadystatechange = function () {};
httpRequest.open('GET', '[http://www.example.org/some.file](http://www.example.org/some.file)', true); httpRequest.send();
参数1 HTTP请求的方法 GET、 POST、 HEAD 等,需大写
参数2 发送请求的URL
参数3 异步选项服务器
若是使用POST方法,则send的参数为想要发送到服务器的任何数据异步
if (httpRequest.readyState === 4) { // Everything is good, the response was received. } else { // Not ready yet. }
请求状态代码函数
经过检查200OK响应代码,区分AJAX调用是否成功code
if (httpRequest.status === 200) { // Perfect! } else { // There was a problem with the request. // For example, the response may have a 404 (Not Found) // or 500 (Internal Server Error) response code. }
在检查请求的状态和响应的HTTP状态代码以后,能够使用服务器发送的数据进行任何所需的操做。对象
httpRequest.responseText - 以文本字符串的形式返回服务器响应
httpRequest.responseXML- 做为XMLDocument能够使用JavaScript DOM函数遍历的对象返回响应ip