如何在没有使用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个回答

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

2

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
单行if语句不需要花括号;没有人使用IE6;这可能是复制粘贴的;使用onload代替onreadystatechange;捕获错误以避免递归调用;xmlhttp是一个可怕的变量名,只需称其为x即可。 - user2039981

1

这里有一个非常好的纯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();

0
快速获取代码,无需使用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)
            }                                 
        }

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