問題描述
Webkit 中的全局 Javascript 變量 (Global Javascript variables in Webkit)
我有 Chrome 7.0 並且正在嘗試訪問全局對象的字段。該代碼在 Firefox 和 IE 中運行良好,但 Chrome 的調試器並沒有幫助我到達任何地方。我試過 Safari,它也有問題。
我可以得到計時器的值,但是當我通過控制台訪問狀態時,我得到 "[object Object]"
。status.completedJobs
即使在 status = $.parseJSON(msg.d);
之後也會返回 undefined
(json 字符串有效)。
我不確定在此之後該怎麼做。從控制台調用 $.parseJSON(msg.d);
可以工作,我可以使用調試器查看對象的字段。如何獲得正確分配和全局可訪問的狀態對象?
//Object that holds result of AJAX request
var status = new Object();
//Refresh timer variables
var timer;
var timer_is_on = 0;
$(document).ready(function() {
update();
doTimer();
});
/**
* Performs the AJAX request and updates the page
*/
function update() {
$.ajax({
type: "POST",
url: "Default.aspx/getStatus",
data: "{}",
contentType: "application/json; charset=utf‑8",
dataType: "json",
success: function(msg) {
if (msg) {
try {
status = $.parseJSON(msg.d);
} catch (e) {
console.log(e);
}
updateProgressBar();
}
}
});
}
function updateProgressBar() {
var percent = Math.round(status.completedJobs / status.numJobs * 100);
$('#progressPercentage').text(percent + '%');
$('#progressbar').progressbar({
value: percent
});
}
/**
* Used to initialize the timer.
*/
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
/**
* Executed on every time interval.
*/
function timedCount() {
update();
timer = setTimeout("timedCount()", 3000);
}
## 參考解法 #### 方法 1:
Try using another name than status, there is a predefined member of window(window is the global object in browser‑based JS) called "status". It also would be good if you assign the global variable to the window‑object to avoid conflicts if there exists a variable in the current (not global) scope with the same name:
window['statusVar'] = $.parseJSON(msg.d);