jquery - 在异步数据获取后更新jquery.sparkline

时间:2011-10-10 01:10:22

标签: javascript jquery jquery-ui asynchronous

背景

我正在使用jquery.sparkline来制作Pie Charts。饼图的数据包含在数组中。

首次加载页面时,将调用Web服务(使用.ajax)来获取数据,此处指定的回调将获取接收的数据并更新与饼图关联的数组。

当屏幕上的下拉列表更改值时,将调用相同的更新过程。

场合

如果我将.ajax调用设置为asynch = false,则一切正常。

如果我将.ajax调用设置为asynch = true,则饼图中显示的结果总是“一次刷新”。通过这个我的意思是最初没有馅饼,然后当下拉列表被更改时,馅饼会以最初的形式呈现。

代码

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: requestURL,
    async:   true ,
    success: function (data) { successCallback(data); },
    error: function (data) { failureCallback(data); }
});

帮助吗 那里的任何人都认识到这个问题?

选项 我一直在观察Observer模式的变化,以监视对数组的更改以及(不确定如何)说服jquery.sparkline对象重绘自己,但这看起来很疯狂,我敢肯定我必须忽略更多的东西简单。



感谢Gareth和他的示例代码,我能够看到我做错了什么(这与jquery.sparkline无关。

我有一些这样的功能:

function RefreshPieChart(){
    //First call managePieDataFetch() 
    //to kick off the web-service request

    managePieDataFetch();

    //now reinitialise the jquery.sparkline
    //pie charts on the basis that the 
    //array variable initialised in 
    //pieDataFetchCallBack() has the newest 
    //data in it.
    //
    //.... It hasn't !
}
function managePieDataFetch(){
    //invoke the .ajax call and 
    //provide function pieDataFetchCallBack() as 
    //a call back function
}
function pieDataFetchCallBack(){
    //post process the data
    //returned from a successful
    //ajax call. Place the results
    //into an array variable at
    //script scope
}

1 个答案:

答案 0 :(得分:7)

我需要看一个更完整的例子来确定问题所在,但是使用async:true对我来说很好。

以下是一个非常简单的工作示例的链接:http://omnipotent.net/jquery.sparkline/ajaxtest.html

ajax方面的来源是: http://omnipotent.net/jquery.sparkline/ajax.phps

如果你的图表被隐藏(即display:none),那么.sparkline()实际上被调用,那么你可能需要在图表被显示的位置调用$ .sparkline_display_visible()来强制它被渲染那时候。