如何运行get json并另存为变量,然后在其他方法中使用它 [英] How to run get json and save as a variable, then use it in other methods

查看:116
本文介绍了如何运行get json并另存为变量,然后在其他方法中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个JSON文件,然后将其数据存储在一个变量中,并在代码的不同部分使用它. 我认为为此目的,我应该使用$.when().done().但是,我不知道如何传递数据. 以下代码不起作用,但显示了我要实现的目标.

I want to parse a JSON file, then store its data in a variable and use it in different part of the code. I think for this purpose I should use $.when().done(). However, I I do not know how to pass data. The following code is not function but it shows what I am trying to achieve.

var myJSON;

function _parseJSON() {
  $.getJSON(settings.json_src).done(function(data) {
    return data;
  });
}

$.when(_parseJSON()).done(function() {
  myJSON = data;
});

function _cacheOptions() {
  console.log(myJSON.data);
};
_cacheDom();
_events();
_render();
....

我需要进行以下操作. 1-获取JSON 2-将其保存在变量中. 3-具有代码中可用的变量以使用其数据.

I need the following happen. 1- get JSON 2- save it in a variable. 3- having the variable available in the code to use its data.

至少需要先准备好JSON数据,然后才能运行几种方法.

At least the JSON data needs to be ready before few methods run.

有什么主意吗?

谢谢.

推荐答案

好吧,您可以改为使用Promises进行链接,并在遍历链时使用传递过来的数据对该数据进行处理.

Well, you could use Promises for chaining instead, and use the data you pass around to do something with that data as you go through your chains.

因此,如果要使用Promise进行示例实现,并处理传递的数据,则可以查看以下代码:

So, if you want a sample implementation using promises, and handling passed around data, you can look at the following code, it:

  • 检索随机图像
  • 因此传递图片网址
  • 该图片网址随后用于预加载图片,并返回图片元素
  • 然后显示图像元素
  • console.log语句已打印

function retrieveData() {
  return $.when( $.getJSON('https://dog.ceo/api/breeds/image/random')
    .then( data => data.message ) );
}

function retrieveImage( source ) {
  return new Promise( (resolve, reject) => {
    const image = new Image();
    image.addEventListener( 'load', function() {
      resolve( image );
    } );
    image.src = source;
  } );
}

function displayImage( image ) {
  document.getElementById('image-container').appendChild( image );
  return Promise.resolve( true );
}

retrieveData()
  .then( retrieveImage )
  .then( displayImage )
  .then( () => console.log('all done') )
  .catch( err => console.error( err ) );
  

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="image-container"></div>

由于一个promise将等待返回的promise完成(或失败),因此所有这些都相继进行,因此在显示元素之前不会打印log语句.

Since a promise will wait for returned promises to complete (or fail), this all goes after each other, so the log statement will not be printed before the element got displayed.

如果1步失败,它将跳至链中的下一个catch.在我的示例中,只有1个陷阱(并且我没有处理 $.getJSON ),因此如果出现问题,应该在控制台中显示错误.

When 1 step fails, it will jump to the next catch in the chain. In my example, there is only 1 catch (and I am not handling errors from $.getJSON), so if something does go wrong, it should print an error in the console.

您当然可以使用 $.when 语句执行几乎相同的操作,因为它返回了Promise

因此,将其应用于代码后,应从解析函数中return $.getJSON,然后基于该链接进行

So applied to your code, you should return the $.getJSON from your parse function, and then chain based on that

var myJSON;

function _parseJSON() {
  // return here, no need returning exactly what you would expect anyhow
  return $.getJSON(settings.json_src);
}

// because you returned, you can chain everything nicely together
$.when( _parseJSON() )
  // don't forget the argument here
  .then(function( data ) { myJSON = data; })
  // and these will only run after the myJSON got set
  .then( _cacheOptions )
  .then( _cacheDom )
  .then( _events )
  .then( _render );

尽管我真的建议不要使用全局变量.如果您在要调用的函数中添加参数,则这些函数将独立于任何不可思议的变量,而可以独立存在

Though I would really suggest not to work with global variables. If you add arguments to the functions you are calling, those functions will become independent from any magical variables, and can stand on their own instead

请注意,如果您的任何链返回了延迟的对象,它将等待该延迟的对象完成.

Note that if any of your chains return a deferred object, it will wait for that deferred object to be completed.

请注意,我们并不是在链中自己调用方法,我们只是传递了函数引用,因此可以按顺序调用它(因此:_events vs _events())

Note that we are not calling the methods ourselves in the chain, we just pass in the function reference, so it can be called in sequence ( so: _events vs _events() )

这篇关于如何运行get json并另存为变量,然后在其他方法中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆