我是JS的新手 - 只想从此开始。
看看这个简单的例子,我想绘制X个量规,其中X是通过Ajax调用从JSON中获取的。
<body>
<div id="gServer"></div><BR>
<script type="text/javascript" language="javascript">
/*
* Obtain number of sessions and Server Status
* Number of sessions is used to draw gauge per session
*/
$.ajax({
url: url,
dataType: 'json',
data: jd,
success: function(data)
{
//
Server_CpuCount = data.Server_Cpu_Count;
Server_LoadAverage = data.Server_Load_Average;
Server_Sessions = data.Server_Sessions_Count;
// Create Gauge for every session connected
for (i = 0; i < Server_Sessions; i++)
{
arr.push(new JustGage({
id: "g"+i,
value: parseFloat(data[i].Session_Load_Average).toFixed(2),
min: 0,
max: data[i].Session_Cpu_Count,
title: data[i].Session_Name,
label: "load"
}));
}
// Create main Server Gauge
gServer = new JustGage({
id: "gServer",
// truncate to 2 digits
value: parseFloat(Server_LoadAverage).toFixed(2),
min: 0,
max: Server_CpuCount,
title: "GridMan Server",
label: "load average"
});
}
});
// Write out label
document.write(Server_Sessions + "<p>sessions</p><BR>");
// Render All Sessions Gauges
// !! It does not work, ajax is async and Server_Sessions is 0
for (i = 0; i < Server_Sessions; i++)
{
document.write("<div id=\"g"+i+"\"></div>");
}
</script>
</body>
这部分不起作用,因为AJAX是异步生成的,因此Server_Sessions始终为0!
for (i = 0; i < Server_Sessions; i++)
{
document.write("<div id=\"g"+i+"\"></div>");
}
如果此变量始终为0,我如何为会话绘制量程?
答案 0 :(得分:0)
最初显示0个会话的量程,并在ajax调用的成功回调函数中使用正确的数字更新它们。这就是你知道你有数据的地方。如果您不希望用户看到0计量器,则隐藏它们直到成功回调并再次显示它们。
答案 1 :(得分:0)
通过在ajax调用中使用回调函数来解决此问题。
$.ajax({
url: url,
dataType: 'json',
data: jd,
success: function(data)
{
//
Server_CpuCount = data.Server_Cpu_Count;
Server_LoadAverage = data.Server_Load_Average;
Server_Sessions = data.Server_Sessions_Count;
// Create main Server Gauge
gServer = new JustGage({
id: "gServer",
// truncate to 2 digits
value: parseFloat(Server_LoadAverage).toFixed(2),
min: 0,
max: Server_CpuCount,
title: "GridMan Server",
label: "load average"
});
// Create Gauge for every session connected
for (i = 0; i < Server_Sessions; i++)
{
// **Add Gauge on to the web page**
$("body").append("<div id=\"g"+i+"\"></div>");
arr.push(new JustGage({
id: "g"+i,
value: parseFloat(data[i].Session_Load_Average).toFixed(2),
min: 0,
max: data[i].Session_Cpu_Count,
title: data[i].Session_Name,
label: "load"
}));
}
}
});