【发布时间】:2015-06-19 11:25:43
【问题描述】:
我想制作一个程序,可以跟踪多个股票对象并显示有关它们的基本信息(即:它们的价格)。
我有这段代码可以成功检索股票价格:
function getStock(symbol, callback){
var url = 'https://query.yahooapis.com/v1/public/yql';
var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
$.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
.done(function (data) {
result = data.query.results.quote.LastTradePriceOnly;
callback(result);
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log('Request failed: ' + err);
});
}
getStock("goog", function(){alert(result)});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我希望能够创建一个可以跟踪股票的简单对象。但是,我遇到了异步和 JSON 请求的问题。这是我的带有“股票”对象的代码:
function getStock(symbol, callback) {
var url = 'https://query.yahooapis.com/v1/public/yql';
var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
$.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
.done(function(data) {
result = data.query.results.quote.LastTradePriceOnly;
callback(result);
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log('Request failed: ' + err);
});
}
function stock(symbol) {
this.price = 0;
getStock(symbol, function(result) { //this function is my callback
console.log(result);
this.price = result;
});
this.printPrice = function() {
alert("The price is: " + this.price);
}
}
var s = new stock("goog");
$("#button").click(function() {
s.printPrice()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>
您可能会注意到,我尝试使用回调,这似乎是解决此问题的合适方法(Javascript 新手)。但是,它似乎并没有真正设置类变量。在控制台中它确实打印了正确的价格,但它似乎并没有改变“this.price”(这是我需要它做的)
关于为什么这不起作用或如何创建“updateStockPrice()”方法的任何建议都会非常有帮助。
【问题讨论】:
-
this在您的回调函数中不再引用this的stock函数。见stackoverflow.com/questions/20279484/…。
标签: javascript jquery asynchronous getjson stocks