gpt4 book ai didi

javascript - 通过异步函数传递变量

转载 作者:行者123 更新时间:2023-11-28 08:10:10 24 4
gpt4 key购买 nike

首先,我使用的是 JQuery。看看:

$(document).ready(function() {
var btcusd = 600;

function getRate() {
$.get("rate.php", function(data) {
var btcArr = JSON.parse(data, true);
btcusd = btcArr["last"];
//This will give me the correct value
console.log(btcusd);
});
}

setInterval(function() {

//This will say 600 every time
console.log(btcusd);

//Update rate for next loop
getRate();

}, 3000);
});

Chrome 控制台每 3 秒给出 600。如果我在 chrome live 控制台中手动执行此操作,我将获得一个真实值,例如 595.32。

为什么这不能按预期工作?感谢您的帮助。

最佳答案

我认为@Tobbe 说得很对。您可以确认的一件事是添加类似 console.log( btcArr ) 的内容,这应该会显示您是否得到了任何返回。

我设置了一个不太不同的演示,一旦 ajax 回调成功更新值,它就永远不会回到 600,这表明该值确实在回调中发生了更改,并且新值在 ajax 外部可用回调。

我使用的ajax代码是:

function getRate() {
var gafa = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=100&q=";
var url = gafa + encodeURI('http://news.yahoo.com/rss/sports/')+"&callback=?";
$.getJSON(url, function(data) {
//var btcArr = JSON.parse(data, true);
var xData = data.responseData.feed.entries
//btcusd = btcArr["last"];
btcusd = xData.length;;
//This will give me the correct value
console.log(btcusd);
});
}

剩下的代码是你的:WORKING JSFIDDLE DEMO

关于javascript - 通过异步函数传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24317652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com