简体   繁体   English

一个基本的香草 javascript AJAX 装载机

[英]A basic vanilla javascript AJAX loader

I am trying to write a simple function to return data from an ajax call.我正在尝试编写一个简单的 function 从 ajax 调用返回数据。 Here is what I have这是我所拥有的

var mytext = "";

function load(url){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send();
    xhr.onloadend = function(e){
        return xhr.responseText;
    }
}

var mytext = load('window.html');

console.log(mytext);

I am stuck, How do I get the returned value?我被卡住了,如何获得返回值? I'ts a function in a function and I am lost:(我是 function 中的 function,我迷路了:(

There are serveral ways to do that.有几种方法可以做到这一点。 Since you seems to be new to javascript, you can start with callback :由于您似乎是 javascript 的新手,您可以从callback开始:

 function load(url, callback){ var xhr = new XMLHttpRequest(); xhr.onloadend = function(e){ callback(xhr); }; xhr.open('GET', url); xhr.send(); } load('/', function (data) { console.log(data); });

In this example, callback is a function, and we pass xhr as a parameter to that function while calling.在此示例中, callback是 function,我们在调用时将xhr作为参数传递给该 function。

My advice is to make use of the Promise and fetch APIs.我的建议是使用Promisefetch API。

function ajax(options) {
  return new Promise(function (resolve, reject) {
    fetch(options.url, {
      method: options.method,
      headers: options.headers,
      body: options.body
    }).then(function (response) {
      response.json().then(function (json) {
        resolve(json);
      }).catch(err => reject(err));
    }).catch(err => reject(err));
  });
}

You can use it like so:你可以像这样使用它:

  const ajaxResponse = await ajax({url: '/some/api/call', method: 'get'});

In case you don't already know, await can only be used inside async functions.如果您还不知道, await只能在async函数中使用。 If you don't want to use async functions, do the following:如果您不想使用async函数,请执行以下操作:

ajax({url: '/some/api/call', method: 'get'}).then(data => {
  // process data here
});

Explanation:解释:

JavaScript is a single-threaded language. JavaScript 是一种单线程语言。 This means everything runs in a blocking manner.这意味着一切都以阻塞方式运行。 If your Ajax call takes 3 seconds, then JavaScript will pause for 3 seconds.如果您的 Ajax 调用需要 3 秒,那么 JavaScript 将暂停 3 秒。 Luckily, the XMLHttpRequest and fetch APIs combat this issue by using asynchronous functions, meaning code can continue running while the Ajax call is awaiting a response.幸运的是, XMLHttpRequestfetch API 通过使用异步函数解决了这个问题,这意味着代码可以在 Ajax 调用等待响应时继续运行。

In your code, you're not getting a response from your function because the Ajax call doesn't stop the execution, meaning by the time the call has been made, there's nothing to return yet and by the time the call is finished, the function's call is long in the past too.在您的代码中,您没有收到来自 function 的响应,因为 Ajax 调用不会停止执行,这意味着在进行调用时,还没有什么可以返回,到调用完成时,函数的调用也是很久以前的事了。 You can tell JavaScript however to keep track of this asynchronous task through Promise s.您可以告诉 JavaScript 但是通过Promise跟踪此异步任务。 When your task is finished, the Promise 's then function is called with the data from the Ajax call.当您的任务完成后,将使用来自 Ajax 调用的数据调用Promise then function 。

JavaScript also provides syntactic sugar to make reading asynchronous code easier. JavaScript 还提供语法糖,使阅读异步代码更容易。 When we use an async function, what we're actually doing is creating a regular function, whose body is wrapped in a Promise .当我们使用async function 时,我们实际上在做的是创建一个常规的 function,其主体包裹在Promise中。

This also means that when you want to wait for the result of a previous Promise , you can prepend await in front of the Promise reference and await the completion of the Promise .这也意味着,当您想要等待前一个Promise的结果时,您可以在Promise引用前面添加await并等待Promise完成。

So you may have code that looks like this:所以你可能有如下代码:

const call = await ajax({ ... });
console.log(call);

which actually translates to the following:这实际上转化为以下内容:

ajax({ ... }).then(call => {
  console.log(call);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM