开发者

javascript unexpected identifier

I am trying to compress my JavaScript code to get less traffic on my site. It has been working fine, but now I came across an error I can't resolve.

I turned my ajax function into one line:

function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){document.getElementById("content").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();}

But the chrome console 开发者_Python百科tells me there is an unexpected identifier on this line. Firefox says there is an semicolon missing on this line.

I have been trying to figure out what is wrong, but I can't find the error, can someone help me with this?


Yes, you have a } too many. Anyway, compressing yourself tends to result in errors.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Use Closure Compiler instead.


I recommend using http://jsbeautifier.org/ - if you paste your code snippet into it and press beautify, the error is immediately visible.


In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()

And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?


Either remove one } from end of responseText;}} or from the end of the line


It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}


If you want to compress JS, I recommend you to use Closure Compiler, a tool provided by Google for website developers. It also provides additional APIs that can be implemented by yourself

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜