简体   繁体   中英

unable to print the username onto console in JavaScript

I have a html file with a linked js

<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. any ideas on how to resolve this? this is 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= … . You should work with two tags:

<script src="{% static 'js/cart.js' %}"/>

  var user = '{{request.user}}';
</script>

if js/cart.js needs to user the user variable, you need to define that first, so:


  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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