Javascript 未捕获的语法错误:Chrome 调试器中出现意外的标识符错误

Javascript Uncaught SyntaxError: Unexpected identifier error in Chrome debugger

本文关键字:错误 标识符 意外 调试器 语法 Javascript Chrome      更新时间:2023-09-26

我正在改编本教程中的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 之后的开始{,以及 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);