简体   繁体   中英

How can I display javascriptfunctions results from one python django template in another?

I have a template in my Python Django project, which has a point counter based on the script below:

function nowScrolling( last_known_scroll_position ) {
            let percentage = last_known_scroll_position / ( window_height - client_height ) 
* 100;
            progressbar.style.right = "calc( 100% - " + Math.round( percentage ) + "% )";
    document.getElementsByClassName('score')[0].innerText= "Congrats! You have just earned " 
+ Math.round(percentage)/2 +" points!";
}

I wonder how to refer the score (function result) on another template / page (Profile, which is going to summarize users points? Thank you very much!

One easy way is by creating an input field in the HTML page where your script is present. Then by using javascript, set the value of input field equal to the result.

document.getElementById("id_of_input_field").value = your_result;

Then by request.get[""] method, you can get the value in your views.py file and store it in the database.Then you can render it wherever you want.

If you don't want to use database to do all the stuff then here is the 2nd way; You should use localStorage function in javascript to store the value of your result in the local storage of the browser. Note that local storage has no expiration date. So that is fine but that is as that is a browser feature, so anybody can edit his/her local storage. Here is the syntax;

localStorage.setItem('result', 'value_of_the_result_from_your_function');

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