I am trying to read data from another file and use this data in HTML (x3d, to be more precise).
In order to do that, I am using $.getJSON to read the data, and $("div").html( "*html code*" )
, using variables inside the html code to display the data in a website.
The problem is that *$("div").html( "html code" )*
is executed before the data is read by $.getJSON.
Here is my code:
<html>
<head>
<title>Superficie soja 63</title>
<script type='text/javascript' src='http://www.x3dom.org/download/x3dom.js'> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel='stylesheet' type='text/css' href='http://www.x3dom.org/download/x3dom.css'></link>
</head>
<body>
<h1>Superficie soja 63</h1>
<div></div>
<script>
var a = [];
var b = [];
var c = [];
var tria = [];
var trib = [];
var tric = [];
var str = "";
var str_tri = "";
$.getJSON("dados_teste.json", function(data) {
for(var cont in data.pontos){
a.push(data.pontos[cont].x);
b.push(data.pontos[cont].y);
c.push(data.pontos[cont].z);
str += (`${a[cont]} ${b[cont]} ${c[cont]}, `);
}
str = str.slice(0, -2);
});
$.getJSON("tri_teste.json", function(data) {
for(var cont in data.triangulos){
tria.push(data.triangulos[cont].tri_a);
trib.push(data.triangulos[cont].tri_b);
tric.push(data.triangulos[cont].tri_c);
str_tri += (`${tria[cont]} ${trib[cont]} ${tric[cont]}, `);
}
str_tri = str_tri.slice(0, -2);
});
setTimeout(() => { console.log(str); }, 1000);
setTimeout(() => { console.log(str_tri); }, 2000);
$("div").html( `
<x3d width='1000px' height='1000px'>
<scene>
<shape>
<appearance>
<ImageTexture
url='https://thumbs.dreamstime.com/b/macro-soybean-food-texture-background-top-view-96368287.jpg'/>
<TextureTransform
translation='0 0'
rotation='0'
repeats='true'
repeatt='true'
scale='80 80'/>
</appearance>
<IndexedTriangleSet
ccw='true'
colorPerVertex='true'
index='${str_tri}'
normalPerVertex='true'
solid='false'
containerField='geometry'>
<Coordinate id="teste"
point='${str}'/>
<Viewpoint
position='0 0 10'
orientation=''
description='camera'/>
</IndexedTriangleSet>
</shape>
</scene>
</x3d> ` )
</script>
</body>
</html>
I already tried using setTimeout()
and delay()
to solve this problem, but it looks like the $.html()
function ignores other functions and is always executed first.
If I simply assign the data directly to the variables, it works. The problem is that I need to read a JSON file to get the data.
How can I solve this problem?
EDITED: I just found out that this problem only happens when I use X3D inside the HTML. With normal HTML, $.html() works fine. But with X3D, the function $.html() doesn't behave properly. So I am still trying to figure out how to solve this problem.