首页 > 解决方案 > 使用 fetch api 传递 url 变量

问题描述

我正在尝试通过 api fetch 传递一个 url 变量,但我无法获得任何结果。谢谢,我是 Javascript 的新手。

//Get IP address
fetch('https://extreme-ip-lookup.com/json/')
  .then((eip) => {
    return eip.json();
  }).then((eip) => {
    document.getElementById('ip').value = eip.query;
    var myip = document.getElementById('ip').value;
    var url = "https://api.pray.zone/v2/times/today.json?ip=" + myip;
  })

//Get City
fetch(url)
  .then((res) => {
    return res.json();
  }).then((res) => {
    document.getElementById('city').value = res.results.location.city;
  })

我可以获取 IP 地址,但不能获取城市。

标签: javascriptjson

解决方案


url仅在.then回调中可见,甚至在您第二次调用fetch.

在那里调用第二个fetch并返回返回的承诺,fetch以便您可以正确链接它们:

//Get IP address
fetch('https://extreme-ip-lookup.com/json/')
  .then((eip) => {
    return eip.json();
  })
  .then((eip) => {
    document.getElementById('ip').value = eip.query;
    var myip = document.getElementById('ip').value;
    return fetch("https://api.pray.zone/v2/times/today.json?ip=" + myip);
  })
  //Get City
  .then((res) => {
    return res.json();
  })
  .then((res) => {
    document.getElementById('city').value = res.results.location.city;
  })

相关:为什么我的变量在函数内部修改后没有改变?- 异步代码参考


推荐阅读