Search code examples
javascriptjqueryhtmlgetscript

jQuery: reading variable from external Javascript file


I'm stuck. I really don't know what I'm doing wrong, but I can't get a string returned to a variable in my embedded Javascript.

token.js:

function token () {
    return "mysecretstring";
}

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TXTURE Server Status</title>
    <script src="http://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        token_val="";
        $.getScript('./token.js', function(data) {
            token_val = token();
            console.log("function: " + token_val);
        });

    </script>

</head>
<body>

</body>
</html>

I can do whatever I want, token_val remains empty. Any hints appreciated.

Best regards, Thomas


Solution

  • I do not use that way to reference a function js. I simply load the library js as same your loads jquery-1.12.4.min.js and then I make the call to the function token() from the script. Code look like that:

    <script src="path_to_project/tokens.js" type="text/javascript"></script>   
    <script type="text/javascript">
       token_val = token();
       console.log("function: " + token_val);
    </script>