Javascript Uncaught SyntaxError:Chrome调试器中出现意外的标识符错误

时间:2011-10-11 21:42:38

标签: javascript google-chrome

我正在调整this tutorialXMLHttpRequest

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调试器在Uncaught SyntaxError: Unexpected identifier上出现else错误。我究竟做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

您错过了之前的结束}以及在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);