如何使用JavaScript进行AJAX调用,而不使用jQuery?


当前回答

你可以根据浏览器获得正确的对象

function getXmlDoc() {
  var xmlDoc;

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlDoc = new XMLHttpRequest();
  }
  else {
    // code for IE6, IE5
    xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
  }

  return xmlDoc;
}

有了正确的对象,GET可以被抽象为:

function myGet(url, callback) {
  var xmlDoc = getXmlDoc();

  xmlDoc.open('GET', url, true);

  xmlDoc.onreadystatechange = function() {
    if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
      callback(xmlDoc);
    }
  }

  xmlDoc.send();
}

并将邮件发送到:

function myPost(url, data, callback) {
  var xmlDoc = getXmlDoc();

  xmlDoc.open('POST', url, true);
  xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xmlDoc.onreadystatechange = function() {
    if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
      callback(xmlDoc);
    }
  }

  xmlDoc.send(data);
}

其他回答

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

我正在寻找一种方法,包括承诺与ajax和排除jQuery。HTML5 Rocks上有一篇文章谈到了ES6的承诺。(您可以使用像Q这样的承诺库填充)您可以使用我从文章中复制的代码片段。

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

注意:我还写了一篇关于这方面的文章。

XMLHttpRequest ()

您可以使用XMLHttpRequest()构造函数创建一个新的XMLHttpRequest(XHR)对象,该对象将允许您使用标准的HTTP请求方法(如GET和POST)与服务器交互:

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

const request = new XMLHttpRequest();

request.addEventListener('load', function () {
  if (this.readyState === 4 && this.status === 200) {
    console.log(this.responseText);
  }
});

request.open('POST', 'example.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

fetch ()

你也可以使用fetch()方法获取一个Promise,它解析为响应对象,表示对请求的响应:

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

fetch('example.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
  body: data,
}).then(response => {
  if (response.ok) {
    response.text().then(response => {
      console.log(response);
    });
  }
});

领航员sendBeacon()。

另一方面,如果你只是试图POST数据,不需要服务器的响应,最短的解决方案是使用navigator.sendBeacon():

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

navigator.sendBeacon('example.php', data);

这是一个没有JQuery的JSFiffle

http://jsfiddle.net/rimian/jurwre07/

function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();
    var url = 'http://echo.jsontest.com/key/value/one/two';

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            } else if (xmlhttp.status == 400) {
                console.log('There was an error 400');
            } else {
                console.log('something else other than 200 was returned');
            }
        }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
};

loadXMLDoc();

使用XMLHttpRequest。

简单的GET请求

httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()

简单的POST请求

httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')

我们可以通过可选的第三个参数指定请求应该是异步(true)(默认值)或同步(false)。

// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)

我们可以在调用httpRequest.send()之前设置头信息

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

我们可以通过设置httpRequest来处理响应。在调用httpRequest.send()之前,onreadystatechange函数

httpRequest.onreadystatechange = function(){
  // Process the server response here.
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      alert(httpRequest.responseText);
    } else {
      alert('There was a problem with the request.');
    }
  }
}