如何在没有jQuery的情况下进行AJAX调用?

dis*_*cky 750 javascript ajax

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

dov*_*mir 575

使用"vanilla"JavaScript:

<script type="text/javascript">
function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

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

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</script>
Run Code Online (Sandbox Code Playgroud)

使用jQuery:

$.ajax({
    url: "test.html",
    context: document.body,
    success: function(){
      $(this).addClass("done");
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 请停止支持IE5/IE6 (930认同)
  • 我实际上定制自己的浏览器,所以它不支持更新的功能.它使用正则表达式来解析所有HTML (19认同)
  • @Archibald你不使用IE5作为主浏览器? (17认同)
  • @JakeSylvestre Netscape永远 (9认同)
  • @DrewNoakes:它肯定更具可读性,但不幸的是,当我在Opera mini浏览器上尝试它时它不受支持,所以我猜它的支持不太普遍 (4认同)
  • @Wade我认为Gokigooooks说当他读到_With"vanilla"JavaScript时,他认为这是一个他需要下载的JavaScript库.他也可能会引用[Vanilla JS](http://vanilla-js.com/). (4认同)

Pet*_*tah 216

使用以下代码段,您可以非常轻松地执行类似的操作,如下所示:

ajax.get('/test.php', {foo: 'bar'}, function() {});
Run Code Online (Sandbox Code Playgroud)

这是片段:

var ajax = {};
ajax.x = function () {
    if (typeof XMLHttpRequest !== 'undefined') {
        return new XMLHttpRequest();
    }
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"
    ];

    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
    return xhr;
};

ajax.send = function (url, callback, method, data, async) {
    if (async === undefined) {
        async = true;
    }
    var x = ajax.x();
    x.open(method, url, async);
    x.onreadystatechange = function () {
        if (x.readyState == 4) {
            callback(x.responseText)
        }
    };
    if (method == 'POST') {
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.send(data)
};

ajax.get = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};

ajax.post = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url, callback, 'POST', query.join('&'), async)
};
Run Code Online (Sandbox Code Playgroud)

  • 停止支持IE 6永远不会使用它. (5认同)
  • @Sam你[通常]不能作为异步请求返回.您应该在回调中处理响应. (2认同)
  • 请将此行包括在内,以包括CORS请求.'xhr.withCredentials = true;' (2认同)

Wil*_*unn 116

我知道这是一个相当古老的问题,但现在有一个更好的API可以在新的浏览器中本地使用.该fetch()方法允许您发出Web请求.例如,从/get-data以下位置请求一些json :

var opts = {
  method: 'GET',      
  headers: {}
};
fetch('/get-data', opts).then(function (response) {
  return response.json();
})
.then(function (body) {
  //doSomething with body;
});
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参见此处

  • 你知道你的浏览器是坏的(IE)当你必须重命名它让人们再次开始使用它时(Edge) (14认同)
  • 实际上,声称Fetch API在"较新的浏览器"中工作是不正确的,因为IE和Edge不支持它.(Edge 14要求用户专门启用此功能)http://caniuse.com/#feat=fetch (9认同)
  • 这里应该提到GitHub的polyfill.https://github.com/github/fetch (7认同)
  • 只需添加`<script src ="https://cdn.rawgit.com/github/fetch/master/fetch.js"> </ script>`并使用fetch作为冠军. (7认同)
  • @saluce现在它在Edge 14中默认启用(IE不再是"新"浏览器:-) (5认同)

Abd*_*ady 103

您可以使用以下功能:

function callAjax(url, callback){
    var xmlhttp;
    // compatible with IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)

您可以在以下链接上在线尝试类似解决方案:

  • @PavelPerna,因为这里的示例是一个“ GET”,所以您可以将它们添加到请求中,但是更笼统地说,我和您在一起,我真的想到了更新答案以接受请求参数作为参数功能,并传递方法(“ GET”或“ POST”),但令我感到沮丧的是,我想在这里将答案尽可能简单,以便人们尽快尝试。实际上,我讨厌其他一些答案,因为它们太长了,因为它们试图变得完美:) (2认同)

Rot*_*eti 40

在普通的ES6/ES2015中这个版本怎么

function get(url) {
  return new Promise((resolve, reject) => {
    const req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
    req.onerror = (e) => reject(Error(`Network Error: ${e}`));
    req.send();
  });
}
Run Code Online (Sandbox Code Playgroud)

该函数返回一个promise.下面是一个如何使用该函数并处理它返回的promise的示例:

get('foo.txt')
.then((data) => {
  // Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
  // Do stuff on error...
});
Run Code Online (Sandbox Code Playgroud)

如果需要加载json文件,可以使用JSON.parse()将加载的数据转换为JS对象.

你也可以集成req.responseType='json'到这个功能,但不幸的是没有IE支持,所以我会坚持JSON.parse().

  • 使用`XMLHttpRequest`进行异步尝试以加载文件.这意味着您的代码执行将继续,而您的文件将在后台加载.为了在脚本中使用文件的内容,您需要一种机制,在文件加载完成或加载失败时告诉您的脚本.这就是*承诺*派上用场的地方.还有其他方法可以解决这个问题,但我认为*promises*最方便. (2认同)
  • @Rotareti你能解释为什么这比"简单"的回调更方便吗?对于旧的浏览器支持,这种便利是否值得花费额外的努力? (2认同)

Raf*_*fay 37

 var xhReq = new XMLHttpRequest();
 xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", false);
 xhReq.send(null);
 var serverResponse = xhReq.responseText;
 alert(serverResponse); // Shows "15"
Run Code Online (Sandbox Code Playgroud)

http://ajaxpatterns.org/XMLHttpRequest_Call

  • 不要做同步通话.使用xhReq.onload并使用回调. (56认同)
  • @FellowStranger oReq.onload = function(){/*this.responseText*/}; (3认同)
  • @kenansulayman同步通话有什么问题?有时它最适合. (3认同)
  • 另外,如果服务器由于某种原因实际上从未响应,则其余代码将永远不会运行。 (2认同)

Har*_*rel 33

使用XMLHttpRequest.

简单的GET请求

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

简单的POST请求

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

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

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

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

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Run Code Online (Sandbox Code Playgroud)

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

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.');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


bru*_*ops 29

您可以根据浏览器获取正确的对象

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;
}
Run Code Online (Sandbox Code Playgroud)

使用正确的对象,可以将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();
}
Run Code Online (Sandbox Code Playgroud)

和POST:

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);
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*ned 17

我正在寻找包括承诺与ajax和排除jQuery.有一篇关于HTML5 Rocks的文章讨论了ES6的承诺(可以使用像Q这样的promise库进行填充),然后使用我从文章中复制的代码片段.

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();
  });
}
Run Code Online (Sandbox Code Playgroud)

注意:我还写了一篇关于此的文章.


tfo*_*ont 15

以下几个例子中的一个小组合创建了这个简单的部分:

function ajax(url, method, data, async)
{
    method = typeof method !== 'undefined' ? method : 'GET';
    async = typeof async !== 'undefined' ? async : false;

    if (window.XMLHttpRequest)
    {
        var xhReq = new XMLHttpRequest();
    }
    else
    {
        var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
    }


    if (method == 'POST')
    {
        xhReq.open(method, url, async);
        xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhReq.send(data);
    }
    else
    {
        if(typeof data !== 'undefined' && data !== null)
        {
            url = url+'?'+data;
        }
        xhReq.open(method, url, async);
        xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhReq.send(null);
    }
    //var serverResponse = xhReq.responseText;
    //alert(serverResponse);
}

// Example usage below (using a string query):

ajax('http://www.google.com');
ajax('http://www.google.com', 'POST', 'q=test');
Run Code Online (Sandbox Code Playgroud)

或者,如果您的参数是对象 - 次要的附加代码调整:

var parameters = {
    q: 'test'
}

var query = [];
for (var key in parameters)
{
    query.push(encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]));
}

ajax('http://www.google.com', 'POST', query.join('&'));
Run Code Online (Sandbox Code Playgroud)

两者都应完全兼容浏览器+版本.


Rya*_*yan 15

如果你不想包含JQuery,我会尝试一些轻量级的AJAX库.

我最喜欢的是reqwest.它只有3.4kb并且内置得很好:https://github.com/ded/Reqwest

以下是reqwest的示例GET请求:

reqwest({
    url: url,
    method: 'GET',
    type: 'json',
    success: onSuccess
});
Run Code Online (Sandbox Code Playgroud)

现在,如果你想要更轻量级的东西,我只需0.4kb即可试用microAjax:https://code.google.com/p/microajax/

这是所有代码:

function microAjax(B,A){this.bindFunction=function(E,D){return function(){return E.apply(D,[D])}};this.stateChange=function(D){if(this.request.readyState==4){this.callbackFunction(this.request.responseText)}};this.getRequest=function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP")}else{if(window.XMLHttpRequest){return new XMLHttpRequest()}}return false};this.postBody=(arguments[2]||"");this.callbackFunction=A;this.url=B;this.request=this.getRequest();if(this.request){var C=this.request;C.onreadystatechange=this.bindFunction(this.stateChange,this);if(this.postBody!==""){C.open("POST",B,true);C.setRequestHeader("X-Requested-With","XMLHttpRequest");C.setRequestHeader("Content-type","application/x-www-form-urlencoded");C.setRequestHeader("Connection","close")}else{C.open("GET",B,true)}C.send(this.postBody)}};
Run Code Online (Sandbox Code Playgroud)

这是一个示例电话:

microAjax(url, onSuccess);
Run Code Online (Sandbox Code Playgroud)


Bla*_*res 13

旧但我会尝试,也许有人会发现这个信息有用.

这是执行GET请求和获取某些JSON格式化数据所需的最少量代码.这仅适用于现代浏览器,如最新版本的Chrome,FF,Safari,OperaMicrosoft Edge.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json'); // by default async 
xhr.responseType = 'json'; // in which format you expect the response to be


xhr.onload = function() {
  if(this.status == 200) {// onload called even on 404 etc so check the status
   console.log(this.response); // No need for JSON.parse()
  }
};

xhr.onerror = function() {
  // error 
};


xhr.send();
Run Code Online (Sandbox Code Playgroud)

另请查看新的Fetch API,它是XMLHttpRequest API的基于承诺的替代品.


Mik*_*ike 9

尝试使用 Fetch Api ( Fetch API )

fetch('http://example.com/movies.json').then(response => response.json()).then(data => console.log(data));
Run Code Online (Sandbox Code Playgroud)

它真的很清楚,而且是 100% 的香草。


Mik*_*kel 8

来自youMightNotNeedJquery.com +JSON.stringify

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)


Gra*_*ler 8

XMLHttpRequest()

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

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);
Run Code Online (Sandbox Code Playgroud)

取()

您还可以使用该fetch()方法来获取,Promise它解析为Response代表对您的请求的响应的对象:

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);
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

navigator.sendBeacon()

另一方面,如果您只是尝试进行POST数据传输并且不需要服务器响应,则最短的解决方案是使用navigator.sendBeacon()

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

navigator.sendBeacon('example.php', data);
Run Code Online (Sandbox Code Playgroud)

  • 我真的很喜欢你的答案,因为你甚至用 XMLHttpRequest 涵盖了大多数情况,甚至对于 Internet Explorer,但我建议在该示例中将:“const data = ...”更改为:“var data = ...” (XMLHttpRequest)所以它完全兼容它 (2认同)

Ash*_*mar 7

这可能有所帮助:

function doAjax(url, callback) {
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

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

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)