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

How to make an AJAX call without jQuery?

如何在不使用jquery的情况下使用javascript进行Ajax调用?


一个JavaScript:"香草"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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();
}

一个jQuery的:

1
2
3
4
5
6
7
$.ajax({
    url:"test.html",
    context: document.body,
    success: function(){
      $(this).addClass("done");
    }
});


使用下面的代码,你可以做类似的东西很容易,像这样:

1
ajax.get('/test.php', {foo: 'bar'}, function() {});

这里是代码段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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)
};


你可以使用以下功能:

1
2
3
4
5
6
7
8
9
10
11
12
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();
}

相似的解决方案,你可以尝试在本文链接:在线

  • http:/ / / / tryit.asp www.w3schools.com XML?第一tryajax _ filename=
  • http:/ / / / tryit.asp www.w3schools.com XML?文件名= tryajax _回调


我知道这是一个相当大的问题,但现在有一个更好的在新的浏览器natively API可用。你让fetch()法允许的Web请求。例如,在一些/get-dataJSON请求:

1
2
3
4
5
6
7
8
9
10
var opts = {
  method: 'GET',      
  headers: {}
};
fetch('/get-data', opts).then(function (response) {
  return response.json();
})
.then(function (body) {
  //doSomething with body;
});

更多的细节在这里。