简体   繁体   English

无法在 JavaScript 中将用户名打印到控制台

[英]unable to print the username onto console in JavaScript

I have a html file with a linked js我有一个带有链接 js 的 html 文件

<script type="text/javascript" src="{% static 'js/cart.js' %}">
  var user= '{{request.user}}'
</script>

and in cart.js i am trying to print the user variable but i keep getting an error saying uncaught ReferenceError user is not defined.在 cart.js 中,我试图打印用户变量,但我不断收到一条错误消息,提示未定义未捕获的 ReferenceError 用户。 any ideas on how to resolve this?关于如何解决这个问题的任何想法? this is cart.js这是 cart.js

var updateBtns=document.getElementsByClassName("update-cart")
for(var i=0;i<updateBtns.length;i++){
    updateBtns[i].addEventListener('click',function(){
        var pid=this.dataset.item
        var action=this.dataset.action
        console.log('pid:',pid,'action:',action)
    })
    console.log('USER',user)
    if(user=='AnonymousUser'){
        console.log('Not logged in')

    }else{
        console.log('User is logged in')
    }
}

According to the w3 organization , if a <script> tag has a src="…" attribute, the content of the script is ignored, so it will never evaluate var user= … .根据w3 组织,如果一个<script>标签有一个src="…"属性,脚本的内容将被忽略,所以它永远不会评估var user= … You should work with two tags:您应该使用两个标签:

<script src="{% static 'js/cart.js' %}"/>
<script>
  var user = '{{request.user}}';
</script>

if js/cart.js needs to user the user variable, you need to define that first, so:如果js/cart.js需要 user user变量,你需要先定义它,所以:

<script>
  var user = '{{request.user}}';
</script>
<script src="{% static 'js/cart.js' %}"/>

I would recommend to add a breakpoint in your browser debugger in the line我建议在您的浏览器调试器中的行中添加一个断点

var user=...

and reload the page.并重新加载页面。 Thus you can see if the line is executed before the card.js script.因此,您可以查看该行是否在 card.js 脚本之前执行。

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

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