我正在调整来自 this tutorial 的 XMLHttpRequest
:
var request = new XMLHttpRequest();
request.open('GET', 'http://www.mozilla.org/', true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
if (request.status == 200)
console.log(request.responseText)
else
console.log('Error', request.statusText);
}
};
request.send(null);
我的代码是:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200)
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
else
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}
}
xhr.send(formData);
但是 Chrome 调试器在 else
上给出了一个 Uncaught SyntaxError: Unexpected identifier
错误。我究竟做错了什么?谢谢!
最佳答案
您缺少 else 之前的结束 }
和 else 之后的开始 {
,以及您的 if-else - 语句中的其他内容。
它适用于您的教程代码,因为 if-else - 语句中只有一行。当有多条线时,你必须正确地阻止它们。 (我个人建议总是这样做,即使只有一行代码。在我看来,它增加了可读性,并且当你有一天决定缩小你的代码时,你不会有问题)
试试这个:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
}else{
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}
}
};
xhr.send(formData);
关于Javascript 未捕获语法错误 : Unexpected identifier error in Chrome debugger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7732887/