简体   繁体   English

Javascript:函数体后面的语法错误

[英]Javascript: Syntax error missing } after function body

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; 我检查了firebug错误控制台,这没有帮助,因为它把我所有的源都放在同一行,我已经通过Lint解析它似乎也没有找到问题 - 我刚刚格式化我的大括号以某种我讨厌的方式不同; 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. 干杯。

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;}

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!

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. 这可能不是您想要的确切解决方案,而是一种定位和修复问题的方法。

在此输入图像描述

Looks like it's being interpreted as being all on one line. 看起来它被解释为全部在一条线上。 See the same results in fiddler2. 在fiddler2中看到相同的结果。

This problem could do due to your JS code having comments being minified. 由于您的JS代码缩小了注释,因此可能会出现此问题。 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 */

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 此处在此代码中,定义函数的var top

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 希望对你有帮助

"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. – " “嗯,我想我找到了一个线索...我正在使用notepad ++并且直到最近才使用我的cpanel文件管理器上传我的文件。一切都很好,直到我使用FireZilla FTP客户端。我假设FTP客户端正在改变我的JS和PHP文件的格式或编码。 - “

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. 在遇到这个愚蠢的bug之后,我刚试了一个不同的FTP客户端,它运行得很完美。 I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well. 我假设我使用的代码(由不同的开发人员编写)也没有正确关闭注释。

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. 看来我在脚本的不同部分使用/**///🜛和一些花哨的unicode char来表示不同的注释。

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. 但是如果在任何js执行之前这个unicode字符和可能的其他字符在注释中的js文件上使用,则错误是随机产生的。

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. 这可能与js文件在被父页面调用和读取之前不是UTF8这一事实有关,当DOM就绪时它是utf8。 Can't tell. 说不出来。

If that can help! 如果这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM