首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Fetch API将jQuery $getJSON调用转换为普通JS

如何使用Fetch API将jQuery $getJSON调用转换为普通JS
EN

Stack Overflow用户
提问于 2022-10-14 11:43:48
回答 1查看 29关注 0票数 1

我有一个网站使用money.js通过从开放货币交换API获取汇率来进行实时货币转换。JSON数据对象包含一个嵌套的'rates‘对象,然后money.js在回调函数中使用该对象获取data.rates并执行转换。

Money.js还提供了一个包装器,需要在应用程序中设置基本货币和转换速率,并将其存储在其fx.rates对象中。然后由API调用的速率覆盖这些设置。

jQuery实现可以工作,但我想将其转换为普通的js。在回调函数试图将fx.rates映射到data.rates之前,Fetch API似乎工作正常,此时我得到了一个错误: TypeError:无法读取未定义的属性(读“rates”)--这是data.rates而不是fx.rates。下面是这两种方法的简化片段:

代码语言:javascript
复制
import money from 'money';

// Jquery Version

(function( $ ) {

  // Declare Default Exchange Rates
  var fx = require("money");

  fx.rates = {
    "EUR" : 1.17, 
    "USD" : 1.39,        
    "GBP" : 1,
  }

  // Init Connect To Open Exchange Rates API

  function initOpenExAPI(){ 

    // Load exchange rates data via AJAX:
    $.getJSON(
      // NB: using Open Exchange Rates here, but you can use any source!
      'https://openexchangerates.org/api/latest.json?app_id=XXXXXXXX&base=GBP',
      function(data) {

        // Check money.js has finished loading:
        if ( typeof fx !== "undefined" && fx.rates ) {
          fx.rates = data.rates; 
          fx.base = data.base;
          
        } else {
          // If not, apply to fxSetup global:
          var fxSetup = {
            rates : data.rates,
            base : data.base, 
          }
        }
        initEuroConversion();
      }
    );          

  }

  //Init Money.js conversion

  function initEuroConversion() {
    $('.js-price').each( function( index, element ){
      var value = $(this).data('price');
      fx(value).from('GBP').to('EUR');
    });
  }

  //Init First Call To Open Exchange API On Ready
  $(document).ready(function () {
    initOpenExAPI();
  });

}( jQuery ) );


/**
* Vanilla JS Version
*/

// Declare Default Exchange Rates
const fx = require('money');

fx.rates = {
  "EUR" : 1.15, 
  "USD" : 1.12,        
  "GBP" : 1,
};

fx.base = "GBP";


/**
 * Init Connect To Open Exchange Rates API
 */
function initOpenExAPI(){ 

  // fetch rates
  fetch('https://openexchangerates.org/api/latest.json?app_id=XXXXXXXX&base=GBP')
   .then(response => response.json())
   .then(json => console.log(json))
   .then(function (data) {

    // Check money.js has finished loading:
    // This is where it fails

    if ( typeof fx !== "undefined" && fx.rates ) {
      fx.rates = data.rates; 
      fx.base = data.base;
      
    } else {
      // If not, apply to fxSetup global:
      const fxSetup = {
        rates : data.rates,
        base : data.base, 
      }
    }
    
    // The API call was successful!
    //console.log(data); returns object
    initEuroConversion();

  })
  .catch(function (err) {
    // There was an error
    console.log('Something went wrong.', err);
  });

}

// Money.js conversion

function initEuroConversion() {

  const subTotal = document.querySelectorAll('.js-price');

  subTotal.forEach(el => {
    const value = el.getAttribute('data-price');
    fx(value).from('GBP').to('EUR');    
  });

}

试图理解为什么使用fetch API的回调函数不能访问fx对象?任何帮助都是很好的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-14 11:57:55

.then(json => console.log(json)) .then(function (data) { // Check money.js has finished loading: // This is where it fails if ( typeof fx !== "undefined" && fx.rates ) { fx.rates = data.rates;

对代码的这一部分中的第一个then的回调:

undefined

  • 接收JavaScript对象(从某些JSON解析但不是JSON本身)

  • 记录它的

  • 返回console.log的返回值,即console.log

第二个then接收前一个then的返回值,即undefined,因此出现错误。

您需要链中的每个then返回要接收的下一个值。

代码语言:javascript
复制
.then(latest => {
    console.log(latest);
    return latest;
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74068694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档