【问题标题】:How to run a JSON after other JSON is loaded加载其他 JSON 后如何运行 JSON
【发布时间】:2019-12-01 23:09:51
【问题描述】:

我正在使用与此问题相同的解决方案。但是,我想在 when() 方法之后加载另一个 JSON 文件。所以在when() 中我得到一个JSON 数据,然后基于此,在then() 方法中,我想加载另一个JSON。

这是我的代码:

var myJSON;
var myJSON2;

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

function _parseJSON2(term) {
  return $.getJSON("http://website.com/" + term ".json");
}

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

myJSON2 = _parseJSON2(data.value); 行必须在加载 data 时运行,并且必须将 myJSON2 保存为变量以供稍后在代码中使用。 这更像是另一个when().then() 是必需的。

知道如何让它工作吗?

提前致谢。

【问题讨论】:

    标签: javascript jquery json jsonp getjson


    【解决方案1】:

    您的 $.when 实际上是多余的,但这并没有真正引起问题

    _parseJSON2(data.value) 缺少的是将其作为承诺返回,同时将其响应分配给myJSON2

    你可以这样做:

    function _parseJSON() {      
      return $.getJSON(settings.json_src)               
    }
    /**
    * Receives data from _parseJSON() and asssigns to myJSON variable
    * Assigns new response to myJSON2
    */
    function _parseJSON2(data) {
      myJSON = data;
      const term = myJSON.value
      return $.getJSON("http://website.com/" + term ".json")
                // this is the then() you were missing
                .then(function(data){
                    myJSON2 = data;
                    // optionally return myJSON2 to next `then()`
                 });
    }
    
    // $.when not really needed
    _parseJSON()
      .then( _parseJSON2 ) 
      .then( _cacheOptions )
      .then( _cacheDom )
      .then( _events )
      .then( _render );
    

    【讨论】:

    • 谢谢。就一个问题。 _parseJSON2 接受和 arg,但我看到你在没有那个的情况下调用它。那可能吗?如果没有,它会得到什么价值?
    • 它确实得到了它,因为它没有在then 中使用匿名函数,而是得到匿名函数得到的参数。记录 data 的日志,其中分配了 myJSON= data...会在那里看到它
    【解决方案2】:

    根据 mozila.org

    如果使用 fetch 函数,则无需使用 jQuery

    fetch("http://website.com/" + term ".json")
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        console.log(JSON.stringify(myJson));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多