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

Javascript 如何在没有jQuery的情况下进行AJAX调用?,javascript,ajax,Javascript,Ajax,如何在不使用jQuery的情况下使用JavaScript进行AJAX调用 使用“香草”JavaScript: xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; xhttp.open("GET", "ajax_info.txt&qu

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

使用“香草”JavaScript:

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
<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>

var xmlDoc=null;
函数加载(){
if(typeof window.ActiveXObject!=“未定义”){
xmlDoc=新的ActiveXObject(“Microsoft.XMLHTTP”);
xmlDoc.onreadystatechange=流程;
}
否则{
xmlDoc=新的XMLHttpRequest();
xmlDoc.onload=进程;
}
open(“GET”,“background.html”,true);
xmlDoc.send(空);
}
函数过程(){
如果(xmlDoc.readyState!=4)返回;
document.getElementById(“输出”).value=xmlDoc.responseText;
}
函数为空(){
document.getElementById(“输出”)。值=“”;
}


负载 清楚的
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>

函数loadXMLDoc()
{
var-xmlhttp;
if(window.XMLHttpRequest)
{//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
其他的
{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
xmlhttp.onreadystatechange=函数()
{
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
document.getElementById(“myDiv”).innerHTML=xmlhttp.responseText;
}
}
open(“GET”,“1.php?id=99freebies.blogspot.com”,true);
xmlhttp.send();
}
让AJAX更改此文本
更改内容
PHP:


使用以下代码片段,您可以非常轻松地完成类似的操作,如:

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)
};
var ajax={};
ajax.x=函数(){
if(XMLHttpRequest的类型!=“未定义”){
返回新的XMLHttpRequest();
}
变量版本=[
“MSXML2.XmlHttp.6.0”,
“MSXML2.XmlHttp.5.0”,
“MSXML2.XmlHttp.4.0”,
“MSXML2.XmlHttp.3.0”,
“MSXML2.XmlHttp.2.0”,
“Microsoft.XmlHttp”
];
var-xhr;
对于(变量i=0;i
您可以使用以下功能:

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();
}
您可以通过以下链接在线尝试类似的解决方案:


您可以使用

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);
}
这可能有助于:

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

下面几个例子的一个小组合,创建了这个简单的作品:

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('&'));
或者如果您的参数是对象-轻微的额外代码调整:

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

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

我正在寻找一种方法,用ajax包含承诺,并排除jQuery。有一篇关于ES6承诺的文章。(您可以使用promise库polyfill,如)您可以使用我从文章中复制的代码片段

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

注意:我也写过。

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

我最喜欢的是西部。它只有3.4kb,而且构造非常完善:

以下是reqwest的示例GET请求:

reqwest({
    url: url,
    method: 'GET',
    type: 'json',
    success: onSuccess
});
现在,如果您想要更轻量级的东西,我会尝试0.4kb的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);

在浏览器中的纯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捆绑模块。您可以使用:


这里有一个没有JQuery的JSF问题

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

我希望有帮助

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

var xmlHttp = createXmlHttpRequestObject();
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;
}
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);
    }
}
步骤2。
检索XMLHttpRequest对象

var xmlHttp = createXmlHttpRequestObject();
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;
}
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);
    }
}
步骤3。
使用XMLHttpRequest对象发出异步HTTP请求

var xmlHttp = createXmlHttpRequestObject();
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;
}
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);
    }
}
步骤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);
        }
    }
}

我知道这是一个相当古老的问题,但现在在本机上有了更好的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;
});

有关更多详细信息,请参阅。

旧版,但我会尝试,也许有人会发现此信息很有用

这是执行
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();

还可以查看new,它是一款基于承诺的替代产品

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();
  });
}
该函数返回一个值。下面是一个关于如何使用函数并处理它返回的承诺的示例:

get('foo.txt')
.then((data) => {
  // Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
  // Do stuff on error...
});
如果需要加载json文件,可以使用它将加载的数据转换为JS对象

您还可以集成到
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));
httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')
// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
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.');
    }
  }
}
/*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();
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);
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);
    });
  }
});
const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

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