如何将变量从一个函数传递到另一个函数

时间:2019-03-28 13:37:19

标签: javascript jquery json

我正在编写一个将数据发送到外部json文件并获取价格的计算器。

功能正常。

问题是我必须从另一个json文件中获取数据并将其插入第二个函数中。

很快,我从json文件中获得折扣,并且必须将该折扣发送到另一个json文件中才能获得价格。

获取折扣看起来像这样:

fetch('discount.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    discountPercent = JSON.stringify(myJson.discount);
console.log(discountPercent); // returns a number, like 15
  });

console.log(discountPercent); // returns discountPercent undefined

discountPercent返回折扣,但仅在该函数内部。

现在我有了第二个获取价格的函数。我将“货币”和“折扣”发送到JSON文件,然后得到一个价格。

function callApi() {

    const output = document.querySelector('#output');
    const url = 'calculate.json';

    const postData = {
    "Currency": "EUR",
    "Discount": "15" // if I put discountPercent instead, it's not working

    };

    fetch(url, {
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(postData)
    }).then(function(response) {
    return response.json();
    }).then(function(result) {
    console.log('result', result);
    output.innerHTML = JSON.stringify(result, null, 2);
    });
}

如果我手动指定折扣,此选项也适用。

我需要以某种方式从第一个功能获得折扣。

类似这样的东西:

"Discount": discountPercent   instead of    "Discount": 15 

我只是找不到将第一个函数的“ discountPercent”值传递给第二个函数的方法。

希望您能提供帮助。

谢谢。

关于, AG

0 个答案:

没有答案
相关问题