代码之家  ›  专栏  ›  技术社区  ›  Streching my competence

AJAX是否可用于不同数据的重用?(无jQuery)[重复]

  •  0
  • Streching my competence  · 技术社区  · 7 年前

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

    0 回复  |  直到 10 年前
        1
  •  630
  •   zb226 Steven Lizarazo    8 年前

    使用“香草”JavaScript:

    <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>
    

    使用jQuery:

    $.ajax({
        url: "test.html",
        context: document.body,
        success: function(){
          $(this).addClass("done");
        }
    });
    
        2
  •  227
  •   Petah    7 年前

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

    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)
    };
    
        3
  •  177
  •   Konstantin    7 年前

    我知道这是一个相当老的问题,但现在在本机上有了一个更好的API newer browsers . 这个 fetch() 方法允许您进行web请求。 例如,从 /get-data

    var opts = {
      method: 'GET',      
      headers: {}
    };
    fetch('/get-data', opts).then(function (response) {
      return response.json();
    })
    .then(function (body) {
      //doSomething with body;
    });
    

    看见 here 更多细节。

        4
  •  107
  •   AbdelHady    9 年前

    您可以使用以下功能:

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

        5
  •  42
  •   Rotareti    9 年前

    这个版本的普通版怎么样 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 . 下面是一个关于如何使用函数和处理 它返回:

    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' 进入函数,但不幸的是 no IE support for it ,所以我会坚持 .

        6
  •  42
  •   julianstark999 adnan Alyaari    5 年前
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert(this.responseText);
        }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send();
    
        7
  •  36
  •   HarlemSquirrel    8 年前

    使用 XMLHttpRequest

    简单获取请求

    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.onreadystatechange 在调用函数之前对函数进行初始化

    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.');
        }
      }
    }
    
        8
  •  30
  •   brunops    12 年前

    您可以根据浏览器使用获取正确的对象

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

    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);
    }
    
        9
  •  17
  •   AlignedDev    5 年前

    我一直在寻找一种方法,用ajax包含承诺并排除jQuery。有一篇关于 HTML5 Rocks 这就是ES6的承诺。(你可以填写一个承诺库,比如 Q )您可以使用我从文章中复制的代码片段。

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

    an article about this .

        10
  •  15
  •   tfont    12 年前

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

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

        11
  •  15
  •   Lonnie Best    10 年前

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

    https://github.com/ded/Reqwest

    以下是reqwest的示例GET请求:

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

    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);
    
        12
  •  14
  •   Grant Miller    7 年前

    XMLHttpRequest()

    你可以使用 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 这就决定了 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()

    邮递 并且不需要服务器响应,最短的解决方案是使用 navigator.sendBeacon() :

    const data = JSON.stringify({
      example_1: 123,
      example_2: 'Hello, world!',
    });
    
    navigator.sendBeacon('example.php', data);
    
        13
  •  13
  •   Blago Eres    10 年前

    但是我会试试,也许有人会发现这些信息很有用。

    这是完成一项任务所需的最少代码量 GET 请求并获取一些 JSON , 游猎 , .

    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 .

        14
  •  9
  •   Mike    5 年前

    Fetch API )

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

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

        15
  •  8
  •   Mikel    8 年前

    从…起 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));
    
        16
  •  7
  •   Ashish Kumar    12 年前

    这可能有助于:

    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();
    }
    
        17
  •  4
  •   Angelos Kapsimanis    14 年前
    <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>
    
        18
  •  4
  •   Prateek Joshi    10 年前

    这只是一个简单的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);
            }
        }
    }
    
        19
  •  3
  •   svnm    10 年前

    在浏览器中的纯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捆绑模块。你可以用 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);
         }
     });
    
        20
  •  3
  •   Rimian    10 年前

    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();
    
        21
  •  3
  •   Karthikeyan Ganesan    8 年前
    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);
           });
    
        22
  •  2
  •   99freebies.blogspot.com    12 年前

    <!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
    
    $id = $_GET[id];
    print "$id";
    
    ?>
    
        23
  •  1
  •   Ir Calif    7 年前

    这里有一个非常好的纯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();
    
        24
  •  0
  •   Rob Kwasowski george    4 年前

    无需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)
                }                                 
            }
    
    推荐文章