股票報價是「資料每隔幾秒就變一次」的典型場景,整頁刷新完全不合理。做法是:用定時器週期性抓取報價,再把解析結果填進表格對應的格子裡,畫面完全不閃動。
function pageInit() {
window.setInterval("ajaxRequest()", 3000); // 每 3 秒更新一次
}
頁面載入時透過 <body onLoad="pageInit();"> 啟動輪詢。
function ajaxRequest() {
$.ajax({
url: 'https://hq.sinajs.cn/list=sh000001,sh601939,sh600016,sh600528',
type: 'GET',
dataType: 'html',
timeout: 2000,
success: function (response) {
var stocks = response.split(';');
for (var i = 0; i < stocks.length - 1; i++) {
var content = stocks[i];
var temp1 = content.split('=')[0];
var temp2 = content.split('=')[1];
var code = temp1.substr(temp1.length - 6, 6);
var temp3 = temp2.replace('"', '');
var name = temp3.split(',')[0];
var tday_f = temp3.split(',')[1]; // 今日開盤
var yest_f = temp3.split(',')[2]; // 昨日收盤
var curr_f = temp3.split(',')[3]; // 當前價格
var temp_f = curr_f - yest_f; // 差價
$('#a' + i).html(code);
$('#b' + i).html(name);
$('#c' + i).html(curr_f > yest_f
? "<font color='red'>" + curr_f + "</font>"
: (curr_f < yest_f
? "<font color='green'>" + curr_f + "</font>"
: curr_f));
$('#d' + i).html(tday_f);
$('#e' + i).html(yest_f);
if (temp_f > 0) {
$('#f' + i).html("<font color='red'>" + temp_f.toFixed(2) + "</font>");
$('#g' + i).html("<font color='red'>" + ((temp_f / yest_f) * 100).toFixed(2) + "</font> %");
} else if (temp_f < 0) {
$('#f' + i).html("<font color='green'>" + temp_f.toFixed(2) + "</font>");
$('#g' + i).html("<font color='green'>" + ((temp_f / yest_f) * 100).toFixed(2) + "</font> %");
} else {
$('#f' + i).html(temp_f.toFixed(2));
$('#g' + i).html(((temp_f / yest_f) * 100).toFixed(2) + " %");
}
$('#h' + i).html(temp3.split(',')[4]); // 最高
$('#i' + i).html(temp3.split(',')[5]); // 最低
}
}
});
}
資料格式是以分號分隔的多筆行情,每筆再用逗號切成欄位,因此解析全靠字串切分。表格則預先備好 nine 欄 × n 列的 <span id="a0"> 到 <span id="i8"> 作為填寫位置,並以 .tr_cls 設定行高與底色。
function ajaxRequest() {
new Ajax.Request(
'https://hq.sinajs.cn/list=sh000001,sh601939,sh600016',
{ method: 'get', onComplete: setData }
);
}
function setData(response) {
var stocks = response.responseText.split(';');
// 其餘解析邏輯相同,改用 $('a'+i).innerHTML 填值
}
用 <font> 上色是當年的寫法,現在一律改用 CSS class(例如 .up / .down),語意清楚也好維護。三秒輪詢對單一使用者沒問題,但同時上線的人一多,請求量會成等比放大;正式環境應在伺服器端加快取,或改用 WebSocket 由伺服器主動推送。跨網域抓資料也要確認對方有開 CORS 標頭,否則瀏覽器會直接攔下。
表格部分完全可以由腳本動態產生,股票清單也能做成可增刪的設定——這些就留給後續迭代了。