【问题标题】:How to handle an ajax request with vanilla JavaScript (ES6)?如何使用 vanilla JavaScript (ES6) 处理 ajax 请求?
【发布时间】:2020-01-18 16:16:33
【问题描述】:

这是我到目前为止的想法:我在尝试打印的 console.log 中什么也没有;虽然也没有错误。 我的目标是使用 vanilla javascript (ES6) 处理一个 ajax 请求(稍后多次)。

  function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://www.website.com/wp-json/acf/v3/options/options', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }
  function init() {
    loadJSON(function(response) {
    // Parse JSON string into object
      var actual_JSON = JSON.parse(response);
      console.log(response)
    });
  }
});

这是我的网站../options... 文件的样子:

{"acf":{"1yr_short_copy":"<p>Our 1 Year Money Back Guarantee either leaves you 100% satisfied,....

因此,例如 - 我只想获取字段 1yr_short_copy 文本数据并打印到 html div 中。我知道这对于 jQuery 来说非常简单;但我无法在当前应用程序上使用 jQuery - 所以我正在寻找 Vanilla ES6 技术.. 有什么想法吗?

【问题讨论】:

  • 如果要使用responseText,需要将xobj上的responseType设置为text。或者,如果您想在xobj.response 中获取 JavaScript 对象而不必使用JSON.parse,请使用json。见Using XMLHttpRequest。但是,您可能想考虑改用Fetch API
  • 是的,如果您不担心 IE 兼容性,请使用 Fetch API
  • 您是否尝试在邮递员中进行测试?我无法从您的服务器获得响应。没有 400,没有 500,没有身份验证错误,完全不行。
  • @HereticMonkey 谢谢;这是有道理的。你到底是什么意思?
  • 您在阅读回复之前设置了responseType。我通常在设置 MIME 类型标头时这样做,因为它们在我的脑海中是相关的。

标签: javascript json ajax ecmascript-6


【解决方案1】:

一半的对象 innit 丢失 ;) 请注意,这是作为 SYNCHRONE 例程。不知何故,到目前为止,我看到了这种类型的电话,你不能使用 post。异步可以工作,但往往会变得复杂。这将从服务器获取任何类型的文件。我在一个小型模板引擎中使用它来包含 html 面包屑甚至更多模板。这样一来,异步函数将是一场噩梦。

function axget(url) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                        // Typical action to be performed when the document is ready:
                        return this.responseText;
                    }
                }
                ;
                // the false below means synchron and works only together with GET 
                xhttp.open("GET", url, false); 
                xhttp.send();

                // by a synchrone funtion we can get the result here
                var src = xhttp.responseText
                if (src === "") {
                    console.log("ERROR AXGET: INVALID OR EMPTY ! " + url);
                }
                return src;
            }

但我只能猜测,这正是您可能需要的 :) 但请注意,这将阻塞,直到此函数获得服务器答案。

异步也是一样

        //writes something inside the document 
        function simplewriter() {
            console.log("Hi i am here !!!!");
            doc = new DOMParser().parseFromString(this.responseText, "text/html");
            document.getElementById(this.id).innerHTML = doc.body.innerHTML;
            this.onload = "";
        }
    //inputdata means some kind for serialized input from a form for example  
    function axg(
                  url, //should be clear
                  inputdata, //serialized datat to be processed by php or whatever
                  execfunc, // the callback function
                  method, //get or post
                  async)  // should be set to true  - its just for testing here
            {
            if (typeof url === 'undefined') {
                return;
            }
            if (typeof async === 'undefined') {
                async = true;
            }
            if (typeof method === 'undefined') {
                method = "GET";
            }
            if (typeof data === 'undefined') {
                inputdata = "";
            }

            xhr = new XMLHttpRequest();
            if (typeof execfunc !== 'undefined') {
                 // here we have to provide a callback function
                 // e.g. the simple writer for example  
                xhr.onload = execfunc.bind(xhr);
            } else {
                return xhr.responseText;
            }
            if (method !== "POST") {
                xhr.open("GET", url, async);
            } else {
            xhr.open("POST", url);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(inputdata, async);
            }
        }

代码将继续运行,不会有任何延迟,并且看起来该函数不存在。这就是需要回调的原因。迟早会在服务器应答时调用此回调函数。但这也意味着它会破坏您的串行代码流。在服务器回答之前,您将看不到任何结果。想象一下,如果你想依赖另一个异步函数的答案……回调噩梦。 这就是为什么我不在我的简单模板系统上使用它的原因。

玩得开心:)

【讨论】:

    【解决方案2】:

    你也可以这样做

    async function ajaxRequest(id) {
      const response = await fetch(`url/${id}`, options); //here is where you do a ajax call
      const json = await response.json(); // here you manage the response
    
      return json;
    }
    

    【讨论】:

    • 谢谢;我已经尝试过以下方法: async function ajaxRequest(id) { const response = await fetch(https://www.website.com/wp-json/acf/v3/options/options/${id}, options); //这里是你调用ajax的地方 const json = await response.json(); // 这里你管理响应返回 json;控制台.log(json); } }); -- 控制台日志中没有任何输出。
    • @CaptainRon 你的 URL 中没有 id,所以不要添加它。 Joaquin 没有善意地更改他的示例以适应您的用例。
    • 作为一个例子,我给出了另一种方式来进行 ajax 调用(使用 fetch),我不太确定你说什么。对不起
    【解决方案3】:

    您可能想使用onsuccess 方法。它是 XMLHttpRequest 类的另一个原型,可在响应转换后工作。

    const text = document.querySelector("#paragraph")
    
    xobj.onsuccess = () => {
        const response = JSON.parse(xobj.responseText);
        text.textContent = response.acf.1yr_short_copy;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2011-12-26
      • 2017-01-29
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      相关资源
      最近更新 更多