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

927

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


23
请注意,虽然这里的许多答案建议监听 _readystatechange_,但现代浏览器支持 XMLHttpRequest 的 load, abort, progresserror 事件(你可能只关心 _load_)。请注意不要改变原文意思,并使翻译更加通俗易懂。 - Paul S.
9
这是一个包含许多纯JavaScript示例(包括IE8+,IE9+和IE10+的AJAX)的网站,它展示了在不使用jQuery的情况下如何完成相同的任务。 - Sanya_Zol
2
w3schools有一个不错的逐步介绍Ajax而不使用jQuery的教程:https://www.w3schools.com/js/js_ajax_intro.asp - MacMartin
您还可以使用EHTML:https://github.com/Guseyn/EHTML 使用e-json元素获取JSON并将其映射到HTML元素。 - Guseyn Ismayylov
24个回答

17

尝试使用Fetch API (Fetch API)。

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

它非常清晰,而且是100%的香草口味。


16

从下面几个示例中简单组合并创建了这个简单的片段:

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');

如果你的参数是对象,只需要进行小的代码调整:

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('&'));

两者都应该完全兼容各种浏览器和版本。


在这里使用hasOwnProperty在for循环内部值得吗? - kibibu

15

如果您不想使用JQuery,可以尝试一些轻量级的AJAX库。

我最喜欢的是reqwest。它只有3.4kb,非常精简:https://github.com/ded/Reqwest

以下是使用reqwest的GET请求示例:

reqwest({
    url: url,
    method: 'GET',
    type: 'json',
    success: onSuccess
});

如果你想要更轻量级的东西,我建议你试试 microAjax,只有 0.4kb: 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)}};

这里是一个示例调用:

microAjax(url, onSuccess);

1
我认为microAjax存在问题,当你调用它两次时(因为有许多“this”,我认为会发生冲突)。 我不知道调用两个“new microAjax”是否是一个好的解决方法,你觉得呢? - Jill-Jênn Vie

13

虽然有些过时,但我会尝试分享一下信息,或许对某些人还是有用的。

以下是你需要的最少量代码,即可进行GET请求并获取一些以JSON格式编码的数据。此方法仅适用于像ChromeFFSafariOperaMicrosoft 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();

另外还要查看新的Fetch API,它是XMLHttpRequest API的基于promise的替代方案。


9

使用 youMightNotNeedJquery.comJSON.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));

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();
}

4

这只是一个4步骤的简单过程,

希望能有所帮助

步骤1. 存储XMLHttpRequest对象的引用

var xmlHttp = createXmlHttpRequestObject();

步骤 2. 获取XMLHttpRequest对象

function createXmlHttpRequestObject() {
    // will store the reference to the XMLHttpRequest object
    var xmlHttp;
    // if running Internet Explorer
    if (window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            xmlHttp = false;
        }
    }
    // if running Mozilla or other browsers
    else {
        try {
            xmlHttp = new XMLHttpRequest();
        } catch (e) {
            xmlHttp = false;
        }
    }
    // return the created object or display an error message
    if (!xmlHttp)
        alert("Error creating the XMLHttpRequest object.");
    else
        return xmlHttp;
}

第三步。使用XMLHttpRequest对象发起异步HTTP请求

function process() {
    // proceed only if the xmlHttp object isn't busy
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        // retrieve the name typed by the user on the form
        item = encodeURIComponent(document.getElementById("input_item").value);
        // execute the your_file.php page from the server
        xmlHttp.open("GET", "your_file.php?item=" + item, true);
        // define the method to handle server responses
        xmlHttp.onreadystatechange = handleServerResponse;
        // make the server request
        xmlHttp.send(null);
    }
}

第四步。 当从服务器接收到消息时,将自动执行

function handleServerResponse() {

    // move forward only if the transaction has completed
    if (xmlHttp.readyState == 4) {
        // status of 200 indicates the transaction completed successfully
        if (xmlHttp.status == 200) {
            // extract the XML retrieved from the server
            xmlResponse = xmlHttp.responseText;
            document.getElementById("put_response").innerHTML = xmlResponse;
            // restart sequence
        }
        // a HTTP status different than 200 signals an error
        else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

4
<html>
  <script>
    var xmlDoc = null ;

  function load() {
    if (typeof window.ActiveXObject != 'undefined' ) {
      xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
      xmlDoc.onreadystatechange = process ;
    }
    else {
      xmlDoc = new XMLHttpRequest();
      xmlDoc.onload = process ;
    }
    xmlDoc.open( "GET", "background.html", true );
    xmlDoc.send( null );
  }

  function process() {
    if ( xmlDoc.readyState != 4 ) return ;
    document.getElementById("output").value = xmlDoc.responseText ;
  }

  function empty() {
    document.getElementById("output").value = '<empty>' ;
  }
</script>

<body>
  <textarea id="output" cols='70' rows='40'><empty></textarea>
  <br></br>
  <button onclick="load()">Load</button> &nbsp;
  <button onclick="empty()">Clear</button>
</body>
</html>

3
在浏览器中使用纯JavaScript:
var xhr = new XMLHttpRequest();

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

xhr.open("GET", "mock_data.json", true);

xhr.send();

如果您想使用node.js将模块捆绑起来,可以使用Browserify。您可以使用superagent

var request = require('superagent');
var url = '/mock_data.json';

 request
   .get(url)
   .end(function(err, res){
     if (res.ok) {
       console.log('yay got ' + JSON.stringify(res.body));
     } else {
       console.log('Oh no! error ' + res.text);
     }
 });

3

这是一个没有使用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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接