简体   繁体   中英

How to display a global javascript variable in typo3 using typoscript?

I would like to output a global variable "elemenId" that is created by a javascript in typo3.

The javascript writes the ID of the touched html element in the global variable elementId:

document.addEventListener("touchstart", (e) => {
                // get elementId of touched element and save as global variable elementId for further processing
                window.elementId = e.target.id;
                });

I would like to display the elementId value in typo3. Is there any chance to access this variable in typo3 using typoscript? Something like:

lib.global_variable = COA_INT
lib.global_variable {
    20 = TEXT
    20.data = GP : elementId
    }

Is there any other way to achieve that? Thanks a lot for your help!

What do you mean with global variable elementId ?
global in what context? PHP? javascript? TYPO3?

You need to distinguish between server(webserver with PHP/TYPO3) and client(Browser with javascript).

How can data be exchanged?

Anything in PHP can be written in the rendering process. The output is HTML, including CSS and javascript. Alternatively TYPO3/PHP can generate other formats like JSON, XML, PDF or CSV.
In this way PHP can transfer some information to Javascript by generating a piece of javascript which assigns the value to a (global) javascript variable:

 $output = '<script>js_var = "' . $php_var . '";</script>';
 echo $output;

Now the client/browser can use the value by executing this javascript code.


On the other hand any value from your client/browser can only be transferred to the server/PHP by doing a new server request. This can be done with a new page request with arguments (either POST or GET) and the server can respond with a appropriate reaction.
Or you do an AJAX call and you will get a appropriate response and some javascript can insert the response in the current document.


Another option would be that javascript only acts locally in the browser and used the information available to generate or modify the current HTML-document. that might be showing the ID of any clicked HTML element in a special HTML object.

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