简体   繁体   中英

How to refresh Javascript variable without page refresh?

I have a Three.JS application that colors the object based on a text file:

let color1 = 0x00ff00;
let color2 = 0xFF04F0;

In the Three.JS code:

var cubeGeometry = new THREE.BoxGeometry(15, 1, 5);
var cubeMaterial = new THREE.MeshLambertMaterial({color:color2});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

var cubeGeometry1 = new THREE.BoxGeometry(15, 1, 5);
var cubeMaterial1 = new THREE.MeshLambertMaterial({color:color1});
var cube1 = new THREE.Mesh(cubeGeometry1, cubeMaterial1);

As the colors in the text file change, the Three.JS application displays them correctly. If I add <META HTTP-EQUIV="refresh" CONTENT="5"> on the <head> of the html then it refreshes and grabs the color values, but the scene resets (notice that you can move the scene with the mouse). Is there a way to update the Javascript variables without reloading the page and keeping the Three.JS scene?

Full code is here: https://github.com/f0n/threeSocket

GitHub pages: https://f0n.github.io/threeSocket/

When you add <META HTTP-EQUIV="refresh" CONTENT="5"> to your HTML document, you're telling it to refresh ALL of it. HTML, DOM updates, JavaScript, its state, variable values... everything. You shouldn't use this approach if you want to maintain your position in the scene.

Why don't you load the HTML page once, then perform timed calls to a server to retreive JUST the color data without doing a full-page refresh? That's what XMLHTTPRequest is for. This is what they call AJAX (Asynchronous Javascript And XML), and there are plenty of StackOverflow questions outlining how to use it.

You may try to refresh the values with setInterval method, so you wont need a full page refresh.

Here is more info

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

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