![](/img/trans.png)
[英]How to pass a variable with url on javascript fetch() method?
[英]pass a url variable with fetch api
我正在尝试通过 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 地址,但不能获取城市。
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;
})
您的代码异步运行,您在获取 url 之前调用了 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;
var url = "https://api.pray.zone/v2/times/today.json?ip=" + myip;
fetch(url)
.then((res) => {
return res.json();
}).then((res) => {
document.getElementById('city').value = res.results.location.city;
})
});
url 变量不在范围内,因此实际上您将 undefined 传递给第二次提取...您可以轻松地将第二次提取放在第一次提取结束之前,或者您在第一次提取之外定义 url 变量并可能将其分配给一个空字符串,然后在关闭第一次提取之前在构建它之后分配 url 值或 url。 那就是如果你想保持 fetch API 的分离方式,就像你现在拥有的那样
嗨,我向我的服务器发送了一个带有变量的 fetch url,我想知道如何使用该变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.