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

How can I make an AJAX call without jQuery?

提问人:discky 提问时间:12/20/2011 最后编辑:SuperStormerdiscky 更新时间:7/15/2023 访问量:871037

问:

如何在不使用 jQuery 的情况下使用 JavaScript 进行 AJAX 调用?

JavaScript AJAX

评论

23赞 Paul S. 4/1/2015
请注意,虽然这里的很多答案都建议监听 readystatechange,但现代浏览器现在支持 XMLHttpRequest 的 load、abortprogresserror 事件(不过你可能只关心 load)。
9赞 Sanya_Zol 5/24/2016
youmightnotneedjquery.com 很多纯 JS 示例,包括 IE8+、IE9+ 和 IE10+ 的 AJAX
2赞 MacMartin 9/29/2017
W3Schools 在没有 jQuery 的情况下逐步介绍了 AJAX: w3schools.com/js/js_ajax_intro.asp
0赞 Guseyn Ismayylov 11/20/2019
您还可以使用 EHTML: github.com/Guseyn/EHTML 使用 e-json 元素获取 json 并将其映射到 html 元素

答:

43赞 Rafay 12/20/2011 #1
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

评论

62赞 19h 5/6/2013
不要进行同步调用。使用 xhReq.onload 并使用回调。
3赞 19h 10/31/2013
@FellowStranger oReq.onload = function () { /*this.responseText*/ };
1赞 mrówa 2/18/2014
@Andrey:没什么,只要你意识到你正在停止执行所有事情,直到服务器的响应返回。没什么特别糟糕的,但对于某些用途来说可能还不够。
2赞 Random Elephant 1/28/2020
此外,如果服务器由于某种原因实际上从未响应,则其余代码将永远不会运行。
664赞 dov.amir 12/20/2011 #2

使用“vanilla”(纯)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

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

评论

1赞 Jay 6/19/2015
@Fractaliste 如果您只是在与 xmlhttp.status 相关的 if 块之后调用回调,那么只需在那里调用它们即可完成。
6赞 Trisped 6/20/2015
@Wade我认为 Gokigooooks 是在说,当他阅读“香草”JavaScript 时,他认为这是一个他需要下载的 JavaScript 库。他可能还引用了 Vanilla JS
4赞 Angelos Kapsimanis 12/20/2011 #3
<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>
2赞 99freebies.blogspot.com 8/6/2013 #4

HTML全文:

<!DOCTYPE html>
    <html>
    <head>
    <script>
    function loadXMLDoc()
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","1.php?id=99freebies.blogspot.com",true);
    xmlhttp.send();
    }
    </script>
    </head>
    <body>

    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>

    </body>
    </html>

PHP格式:

<?php

$id = $_GET[id];
print "$id";

?>

评论

1赞 12/21/2015
单行 ifs 不需要大括号,Noone 使用 IE6,这可能是复制粘贴的,使用 onload 而不是 onreadystatechange,捕获可能的递归调用错误,xmlhttp 是一个可怕的变量名称,只需将其命名为 x。
231赞 Petah 8/6/2013 #5

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

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

以下是代码片段:

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赞 Sam 8/13/2014
这是一个非常好的起点,但我认为你错过了@3nigma答案中的某些内容。也就是说,我不确定在不返回服务器响应的情况下发出某些请求(所有 get 和一些 post)有多大意义。我在 send 方法的末尾添加了另一行-- --然后返回每个调用。return x.responseText;ajax.send
3赞 Petah 8/13/2014
@Sam您 [通常] 不能返回异步请求。您应该在回调中处理响应。
0赞 Petah 8/14/2014
@Sam里面有一个例子:ajax.get('/test.php', {foo: 'bar'}, function(responseText) { alert(responseText); });
0赞 afsantos 9/13/2014
不错的片段。但是,不应该是吗?query.join('&').replace(/%20/g, '+')
3赞 Akam 3/2/2016
请同时包含 CORS 请求,将此行作为选项。'xhr.withCredentials = true;'
109赞 AbdelHady 8/20/2013 #6

您可以使用以下函数:

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

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

评论

0赞 Pavel Perna 10/18/2016
为请求添加一些输入变量也很好(将在xmlhttp.send(request)中使用);
2赞 AbdelHady 10/19/2016
@PavelPerna,由于这里的示例是一个 ,所以你可以将它们添加到请求中,但更一般地说,我和你在一起,我真的想过更新答案以接受请求参数作为此处函数的参数,并且还传递方法(或),但阻止我的是我想让这里的答案尽可能简单,以便人们尽快尝试。实际上,我讨厌其他一些答案太长,因为它们试图成为完美的:)GETGETPOST
30赞 brunops 9/25/2013 #7

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

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);
}
7赞 Ashish Kumar 11/30/2013 #8

这可能会有所帮助:

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();
}
16赞 tfont 2/25/2014 #9

下面几个例子的一个小组合,创造了这个简单的部分:

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

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

评论

0赞 kibibu 2/13/2015
是否值得在for循环中使用hasOwnProperty?
18赞 AlignedDev 10/8/2014 #10

我一直在寻找一种方法来包含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();
  });
}

注意:我还写了一篇关于这个的文章

15赞 Ryan Shea 2/4/2015 #11

如果你不想包含 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赞 Jill-Jênn Vie 5/24/2015
我认为microAjax有问题,当你调用它两次时(因为有无数的“this”,我认为,一定有冲突)。我不知道将两个称为“新 microAjax”是否是一个很好的解决方法,是吗?
3赞 svnm 4/27/2015 #12

在浏览器中的纯 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();

或者,如果您想使用 Browserify 使用 node.js 捆绑您的模块。您可以使用超级代理

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赞 Rimian 5/18/2015 #13

这是一个没有 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();
4赞 Prateek Joshi 6/21/2015 #14

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

我希望它有所帮助

Step 1.存储对 XMLHttpRequest 对象的引用

var xmlHttp = createXmlHttpRequestObject();

Step 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;
}

Step 3.使用 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);
    }
}

Step 4.从服务器接收到消息时自动执行

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);
        }
    }
}
223赞 Will Munn 8/13/2015 #15

现在,现代浏览器中原生提供了一个更好的 Fetch API。该方法允许您发出 Web 请求。 例如,要从以下位置请求一些 JSON:fetch()/get-data

let options = {
  method: 'GET',      
  headers: {}
};

fetch('/get-data', options)
.then(response => response.json())
.then(body => {
  // Do something with body
});

有关更多详细信息,请参阅 MDN Web 文档:使用 Fetch API

异步/等待

或者,如果使用 和 语法,请执行以下操作:asyncawait

async function doApi(url) {
  const response = await fetch(url);
  if( response.ok ) {
    if( 200 <= response.status && response.status <= 299 ) {
      const result = await response.json();
      // do something awesome with result
    } else {
      console.log( `got a ${response.status}` );
    }
  }
}

当然,您可能想检查响应代码等,但文档对此进行了非常详细的介绍。

评论

9赞 TylerY86 9/29/2016
这里应该提到 GitHub 的 polyfill。github.com/github/fetch
10赞 TylerY86 9/29/2016
只需像冠军一样添加和使用 fetch。<script src="https://cdn.rawgit.com/github/fetch/master/fetch.js"></script>
1赞 Kenny Lim 1/19/2017
请勿在移动设备上使用 Fetch。它在 Android 上存在 HTTP 标头小写问题。在 iOS 上运行良好。
13赞 Blago Eres 9/27/2015 #16

老了,但我会尝试,也许有人会发现这些信息有用。

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

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 的替代品。

42赞 Rotareti 8/22/2016 #17

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

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

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

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

您也可以将 req.responseType='json' 集成到函数中,但不幸的是没有 IE 支持它,所以我会坚持使用 .JSON.parse()

评论

2赞 Rotareti 8/29/2016
使用异步尝试加载文件。这意味着您的代码将继续执行,而您的文件将在后台加载。为了在脚本中使用文件的内容,您需要一种机制来告知脚本文件何时完成加载或加载失败。这就是承诺派上用场的地方。还有其他方法可以解决这个问题,但我认为承诺是最方便的。XMLHttpRequest
0赞 bodruk 1/25/2017
@Rotareti 移动浏览器是否支持这种方法?
0赞 Rotareti 1/25/2017
只有较新的浏览器版本才支持它。一种常见的做法是用最新的 ES6/7/ 编写代码。并使用 Babel 或类似工具将其转译回 ES5 以获得更好的浏览器支持。
2赞 lennyklb 4/24/2017
@Rotareti 您能解释一下为什么这比“简单”回调更方便吗?这种便利是否值得付出额外的努力来转译它以获得旧的浏览器支持?
0赞 Rotareti 4/24/2017
@LennartKloppenburg我认为这个答案很好地解释了这一点:stackoverflow.com/a/14244950/1612318“这种便利是否值得付出额外的努力来转译它以获得旧的浏览器支持?Promise 只是 ES6/7 附带的众多功能之一。如果你使用转译器,你可以编写最新的 JS。这是值得的!
3赞 Karthikeyan Ganesan 12/9/2016 #18
var load_process = false;
function ajaxCall(param, response) {

 if (load_process == true) {
     return;
 }
 else
 { 
  if (param.async == undefined) {
     param.async = true;
 }
 if (param.async == false) {
         load_process = true;
     }
 var xhr;

 xhr = new XMLHttpRequest();

 if (param.type != "GET") {
     xhr.open(param.type, param.url, true);

     if (param.processData != undefined && param.processData == false && param.contentType != undefined && param.contentType == false) {
     }
     else if (param.contentType != undefined || param.contentType == true) {
         xhr.setRequestHeader('Content-Type', param.contentType);
     }
     else {
         xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
     }


 }
 else {
     xhr.open(param.type, param.url + "?" + obj_param(param.data));
 }

 xhr.onprogress = function (loadTime) {
     if (param.progress != undefined) {
         param.progress({ loaded: loadTime.loaded }, "success");
     }
 }
 xhr.ontimeout = function () {
     this.abort();
     param.success("timeout", "timeout");
     load_process = false;
 };

 xhr.onerror = function () {
     param.error(xhr.responseText, "error");
     load_process = false;
 };

 xhr.onload = function () {
    if (xhr.status === 200) {
         if (param.dataType != undefined && param.dataType == "json") {

             param.success(JSON.parse(xhr.responseText), "success");
         }
         else {
             param.success(JSON.stringify(xhr.responseText), "success");
         }
     }
     else if (xhr.status !== 200) {
         param.error(xhr.responseText, "error");

     }
     load_process = false;
 };
 if (param.data != null || param.data != undefined) {
     if (param.processData != undefined && param.processData == false && param.contentType != undefined && param.contentType == false) {
             xhr.send(param.data);

     }
     else {
             xhr.send(obj_param(param.data));

     }
 }
 else {
         xhr.send();

 }
 if (param.timeout != undefined) {
     xhr.timeout = param.timeout;
 }
 else
{
 xhr.timeout = 20000;
}
 this.abort = function (response) {

     if (XMLHttpRequest != null) {
         xhr.abort();
         load_process = false;
         if (response != undefined) {
             response({ status: "success" });
         }
     }

 }
 }
 }

function obj_param(obj) {
var parts = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
    }
}
return parts.join('&');
}

我的 Ajax 调用

  var my_ajax_call=ajaxCall({
    url: url,
    type: method,
    data: {data:value},
    dataType: 'json',
    async:false,//synchronous request. Default value is true 
    timeout:10000,//default timeout 20000
    progress:function(loadTime,status)
    {
    console.log(loadTime);
     },
    success: function (result, status) {
      console.log(result);
    },
      error :function(result,status)
    {
    console.log(result);
     }
      });

对于中止以前的请求

      my_ajax_call.abort(function(result){
       console.log(result);
       });
9赞 Mikel 7/24/2017 #19

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));
38赞 HarlemSquirrel 12/29/2017 #20

使用 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.onreadystatechangehttpRequest.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.');
    }
  }
}

评论

1赞 Nate Vaughan 11/4/2019
请注意,除了 200 之外,还有其他成功状态,例如 201
1赞 Ir Calif 8/7/2018 #21

这里有一个纯 javascript 的非常好的解决方案

/*create an XMLHttpRequest object*/

let GethttpRequest=function(){  
  let httpRequest=false;
  if(window.XMLHttpRequest){
    httpRequest   =new XMLHttpRequest();
    if(httpRequest.overrideMimeType){
    httpRequest.overrideMimeType('text/xml');
    }
  }else if(window.ActiveXObject){
    try{httpRequest   =new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
      try{
        httpRequest   =new ActiveXObject("Microsoft.XMLHTTP");
      }catch(e){}
    }
  }
  if(!httpRequest){return 0;}
  return httpRequest;
}

  /*Defining a function to make the request every time when it is needed*/

  function MakeRequest(){

    let uriPost       ="myURL";
    let xhrPost       =GethttpRequest();
    let fdPost        =new FormData();
    let date          =new Date();

    /*data to be sent on server*/
    let data          = { 
                        "name"      :"name",
                        "lName"     :"lName",
                        "phone"     :"phone",
                        "key"       :"key",
                        "password"  :"date"
                      };

    let JSONdata =JSON.stringify(data);             
    fdPost.append("data",JSONdata);
    xhrPost.open("POST" ,uriPost, true);
    xhrPost.timeout = 9000;/*the time you need to quit the request if it is not completed*/
    xhrPost.onloadstart = function (){
      /*do something*/
    };
    xhrPost.onload      = function (){
      /*do something*/
    };
    xhrPost.onloadend   = function (){
      /*do something*/
    }
    xhrPost.onprogress  =function(){
      /*do something*/
    }

    xhrPost.onreadystatechange =function(){

      if(xhrPost.readyState < 4){

      }else if(xhrPost.readyState === 4){

        if(xhrPost.status === 200){

          /*request succesfull*/

        }else if(xhrPost.status !==200){

          /*request failled*/

        }

      }


   }
  xhrPost.ontimeout = function (e){
    /*you can stop the request*/
  }
  xhrPost.onerror = function (){
    /*you can try again the request*/
  };
  xhrPost.onabort = function (){
    /*you can try again the request*/
  };
  xhrPost.overrideMimeType("text/plain; charset=x-user-defined-binary");
  xhrPost.setRequestHeader("Content-disposition", "form-data");
  xhrPost.setRequestHeader("X-Requested-With","xmlhttprequest");
  xhrPost.send(fdPost);
}

/*PHP side
<?php
  //check if the variable $_POST["data"] exists isset() && !empty()
  $data        =$_POST["data"];
  $decodedData =json_decode($_POST["data"]);
  //show a single item from the form
  echo $decodedData->name;

?>
*/

/*Usage*/
MakeRequest();
17赞 Grant Miller 3/21/2019 #22

XMLHttp请求()

您可以使用 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,该 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);
    });
  }
});

navigator.sendBeacon()

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

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

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

评论

2赞 Dazag 7/9/2019
我真的很喜欢你的回答,因为你涵盖了大多数情况,即使是带有 XMLHttpRequest 的 Internet Explorer,但我建议更改:“const data = ...”成为:“var data = ...”在该示例 (XMLHttpRequest) 上,因此它与它完全兼容
17赞 Mike 6/8/2020 #23

尝试使用 Fetch Api (Fetch API)

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

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

0赞 Wprog_dy 6/30/2021 #24

无需jQuery即可快速获取代码

async  function product_serach(word) {
            var response = await fetch('<?php echo base_url(); ?>home/product_search?search='+word);
            var json = await response.json();
            for (let [key, value] of Object.entries(json)) 
            {
                console.log(json)
            }                                 
        }