我构建了一个简单的Web应用程序,它从ebay API获取一些数据(JSON),并将结果绘制到显示每个项目价格的图表上。这很好用。
但是,如果某个项目出价或完成,我希望图表能够实时更新。所有这些数据都包含在ebay返回的JSON中。
我的问题是如何让图表更新,以及调用ajax作为JSON更改(这是理想的方法)还是每隔1到5秒说一次?
$(function() {
$.ajax({
type: "GET",
url: 'http://open.api.ebay.com/shopping?callname=GetMultipleItems&responseencoding=JSON&appid=&siteid=3&ItemID=350720045158,390524810753,251237014268,200902751277,140927144371&version=811',
dataType: "jsonp",
jsonp: "callbackname",
crossDomain : true,
data: { },
success: function (result) {
arrayOfData = new Array();
var items = result['Item'];
$.each(items, function(i, item) {
var title = items[i]['Title'];
var price = items[i]['ConvertedCurrentPrice']['Value'];
var timeleft = items[i]['TimeLeft'];
arrayOfData.push(['400', title + '<br/><br />' + timeleft]);
});
$('#graph').jqBarGraph({
data: arrayOfData,
height: 800,
width: 1200,
barSpace: 20,
colors: ['#085497','#74b3ea'],
prefix: '£'
});
},
error: function (data) {
console.log(arguments);
}
});
});
答案 0 :(得分:3)
在setInterval中放置ajax请求:
setInterval(function(){
//ajax request here
}, 5 * 1000);
答案 1 :(得分:0)
如果你只是想在价格变化时做出反应,你可以做这样的事情。这非常粗糙,但我只想向您展示一个指南:
$(function() {
var last_price = {}; // object to keep track of previous prices
// factored out function
var update_chart = function (data_to_be_plotted)
{
$('#graph').jqBarGraph({
data: data_to_be_plotted,
height: 800,
width: 1200,
barSpace: 20,
colors: ['#085497','#74b3ea'],
prefix: '£'
});
};
$.ajax({
//...bla bla bla...
success: function (result) {
arrayOfData = new Array();
var items = result['Item'];
$.each(items, function(i, item) {
var title = items[i]['Title'];
var price = items[i]['ConvertedCurrentPrice']['Value'];
// if this item was not registered before, or the price is different
if (! last_price[title] || last_price[title] !== price)
{
// this you have to adapt to your own needs
arrayOfData.push(title + '<br/><br />' + price);
}
// register the price for the item, so that you know the next time
last_price[title] = price;
});
if (arrayOfData.length > 0) // i.e.: something new came
{
update_chart(arrayOfData);
}
});
});