ajax奇怪的错误:未捕获的SyntaxError:意外的令牌if

时间:2011-12-29 13:51:41

标签: javascript ajax

我有这个javascript:

function updatePage() {   
if (request.readyState == 4)
    if (request.status == 200)
        var data = JSON.parse(request.responseText);
        update_select($('select[name=island_name]'), data);
    else if (request.status == 404)
        alert("Request url does not exist");
    else
        alert("Error: status code is " + request.status);
}  

但是我一直收到Uncaught SyntaxError: Unexpected token if错误,这会导致我的脚本暂停。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

function updatePage() {   
if (request.readyState == 4)
    if (request.status == 200)
    {
        var data = JSON.parse(request.responseText);
        update_select($('select[name=island_name]'), data);
    }
    else if (request.status == 404)
        alert("Request url does not exist");
    else
        alert("Error: status code is " + request.status);
}

您缩进了第5行(update_select...),但它实际上并不在if

答案 1 :(得分:1)

你错过了大括号{第2行和第3行:

function updatePage() {   
   if (request.readyState == 4) {
      if (request.status == 200) {
          var data = JSON.parse(request.responseText);
          update_select($('select[name=island_name]'), data);
      }
      else if (request.status == 404)
         alert("Request url does not exist");
      else
        alert("Error: status code is " + request.status);
    }
} 

答案 2 :(得分:1)

你错过了一堆大括号,在update_select()行,它引起了一个问题。大多数这些块并不严格要求大括号,但是因为你试图在第一个if()中执行两个语句,所以你需要它们。最好将它们放在任何地方。

function updatePage() {   
  if (request.readyState == 4) {
    if (request.status == 200) {
        var data = JSON.parse(request.responseText);
        // Second statement executed after the if() 
        // MUST use {} on this block
        update_select($('select[name=island_name]'), data);
    }
    else if (request.status == 404) {
        alert("Request url does not exist");
    }
    else {
        alert("Error: status code is " + request.status);
    }
  }
}