Javascript: Syntax error missing } after function body

末鹿安然 提交于 2021-02-07 13:17:33

问题


Ok, so you know the error, but why on earth am I getting it? I get no errors at all when this is run locally but when I uploaded my project I got this annoying syntax error. I've checked firebug error console, which doesn't help because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.

function ToServer(cmd, data) {
    var xmlObj = new XMLHttpRequest();
    xmlObj.open('POST', 'handler.php', true);
    xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlObj.send(cmd + data);
    xmlObj.onreadystatechange = function() {
        if(xmlObj.readyState === 4 && xmlObj.status === 200) {
            if(cmd == 'cmd=push') {
                document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
            }
            if(cmd == 'cmd=pop') {
                document.getElementById('messages').innerHTML += xmlObj.responseText;
            }
            if(cmd == 'cmd=login') {
                if(xmlObj.responseText == 'OK') {
                    self.location = 'index.php';
                }
                else {
                    document.getElementById('response').innerHTML = xmlObj.responseText;
                }
            }           
        }
    }
}

function Login() {
    // Grab username and password for login
    var uName = document.getElementById('uNameBox').value;
    var pWord = document.getElementById('pWordBox').value;
    ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}


// Start checking of messages every second
window.onload = function() {
    if(getUrlVars()['to'] != null) {
        setInterval(GetMessages(), 1000);
    }
}

function Chat() {
    // Get username from recipient box
    var user = document.getElementById('recipient').value;
    self.location = 'index.php?to=' + user;
}

function SendMessage() {
    // Grab message from text box
    var from = readCookie('privateChat');
    var to = getUrlVars()['to'];
    var msg = document.getElementById('msgBox').value;
    ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
    // Reset the input box
    document.getElementById('msgBox').value = "";
}

function GetMessages() {
    // Grab account hash from auth cookie
    var aHash = readCookie('privateChat');
    var to = getUrlVars()['to'];
    ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
    var textArea = document.getElementById('messages');
    textArea.scrollTop = textArea.scrollHeight;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

One gold internet medal to whoever can solve this.

Cheers.


回答1:


The problem is your script in your server is in one line, and you have comments in it. the code after // will be considered as comment. That's the reason.

function ToServer(cmd, data) {  var xmlObj = new XMLHttpRequest();  xmlObj.open('POST', 'handler.php', true);   xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');   xmlObj.send(cmd + data);    xmlObj.onreadystatechange = function() {        if(xmlObj.readyState === 4 && xmlObj.status === 200) {          if(cmd == 'cmd=push') {             document.getElementById('pushResponse').innerHTML = xmlObj.responseText;            }           if(cmd == 'cmd=pop') {              document.getElementById('messages').innerHTML += xmlObj.responseText;           }           if(cmd == 'cmd=login') {                if(xmlObj.responseText == 'OK') {                   self.location = 'index.php';                }               else {                  document.getElementById('response').innerHTML = xmlObj.responseText;                }           }                   }   };}function Login() {   // Grab username and password for login var uName = document.getElementById('uNameBox').value;  var pWord = document.getElementById('pWordBox').value;  ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() {    if(getUrlVars()['to'] != null) {        setInterval(GetMessages(), 1000);   }}function Chat() { // Get username from recipient box  var user = document.getElementById('recipient').value;  self.location = 'index.php?to=' + user;}function SendMessage() {    // Grab message from text box   var from = readCookie('privateChat');   var to = getUrlVars()['to'];    var msg = document.getElementById('msgBox').value;  ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box  document.getElementById('msgBox').value = "";}function GetMessages() {  // Grab account hash from auth cookie   var aHash = readCookie('privateChat');  var to = getUrlVars()['to'];    ToServer('cmd=pop','&account=' + aHash + '&to=' + to);  var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) {    var nameEQ = name + "=";    var ca = document.cookie.split(';');    for(var i=0;i < ca.length;i++) {        var c = ca[i];        while (c.charAt(0)==' ') c = c.substring(1,c.length);        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);    }    return null;}function getUrlVars() {    var vars = {};    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {        vars[key] = value;    });    return vars;}



回答2:


I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming if not remove the first portion and see. This is a technique which I follows when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.

This will help us to identify the actual point of error.

I do not see any problem with this script.

This may not be the exact solution you want but a way to locate and fix your problem.




回答3:


enter image description here

Looks like it's being interpreted as being all on one line. See the same results in fiddler2.




回答4:


You're missing a semi-colon:

function ToServer(cmd, data) {
    var xmlObj = new XMLHttpRequest();
    xmlObj.open('POST', 'handler.php', true);
    xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlObj.send(cmd + data);
    xmlObj.onreadystatechange = function() {
        if(xmlObj.readyState === 4 && xmlObj.status === 200) {
            if(cmd == 'cmd=push') {
                document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
            }
            if(cmd == 'cmd=pop') {
                document.getElementById('messages').innerHTML += xmlObj.responseText;
            }
            if(cmd == 'cmd=login') {
                if(xmlObj.responseText == 'OK') {
                    self.location = 'index.php';
                }
                else {
                    document.getElementById('response').innerHTML = xmlObj.responseText;
                }
            }           
        }
    }; //<-- Love the semi
}

Additional missing semi-colon:

// Start checking of messages every second
window.onload = function() {
    if (getUrlVars()['to'] != null) {
        setInterval(GetMessages(), 1000);
    }
}; //<-- Love this semi too!



回答5:


This problem could do due to your JS code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:

// Reset the input box

...to...

/* Reset the input box */




回答6:


Seems there should be added another semi in the following code too

// Start checking of messages every second
window.onload = function() {
    if(getUrlVars()['to'] != null) {
        setInterval(GetMessages(), 1000);
    }
};  <---- Semi added

Also here in this code, define the var top of the function

function readCookie(name) {
    var i;
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

Hope this will help you




回答7:


"Hm I think I found a clue... I'm using notepad++ and have until recently used my cpanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "

I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.




回答8:


Adding a note: very strangly this error was there very randomly, with everything working fine.

Syntax error missing } after function body | At line 0 of index.html

It appear that I use /**/ and //🜛 with some fancy unicode char in different parts of my scripts for different comments.

This is useful to me, for clarity and for parsing.

But if this unicode character and probably some others are used on a js file in comments before any js execution, the error was spawning randomly.

This might be linked to the fact that js files aren't UTF8 before being called and read by the parent page, it is utf8 when DOM ready. Can't tell.

If that can help!



来源:https://stackoverflow.com/questions/11945216/javascript-syntax-error-missing-after-function-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!