簡體   English   中英

jQuery function $.html() 不等待其他代碼行完成

[英]jQuery function $.html() does not wait for other lines of code to finish

我正在嘗試從另一個文件中讀取數據並在 HTML(更准確地說是 x3d)中使用這些數據。

為此,我使用 $.getJSON 讀取數據,並使用$("div").html( "*html code*" )使用 html 代碼中的變量在網站中顯示數據。

問題是 * $("div").html( "html code" )*$.getJSON讀取數據之前執行。

這是我的代碼:

<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>

我已經嘗試使用setTimeout()delay()來解決這個問題,但看起來$.html() function 忽略了其他函數,總是先執行。

如果我只是將數據直接分配給變量,它就可以工作。 問題是我需要讀取 JSON 文件來獲取數據。

我怎么解決這個問題?

已編輯:我剛剛發現只有在 HTML 中使用 X3D 時才會出現此問題。 對於正常的 HTML,$.html() 可以正常工作。 但是對於 X3D,function $.html() 行為不正常。 所以我還在想辦法解決這個問題。

我嘗試使用 javascript 以多種不同的方式使此代碼工作,並發現問題出在 X3D 上。 到目前為止發布的所有答案都有意義,但是當 HTML 代碼中包含 X3D 時,它們不起作用。

所以我決定改用 PHP,現在它可以工作了!

<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> 

        <?php
            $path = "dados_teste.json";
            $file = fopen($path, "r");
            $data="";
            while(!feof($file)){
                $data .= fread($file, filesize($path));
            }
            fclose($file);
            $data= json_decode($data, true);
            $str="";
            for($cont=0; $cont < count($data["pontos"]); $cont++){
                if($cont < count($data["pontos"])-1)
                    $str .= ($data["pontos"][$cont]["x"] . " " . $data["pontos"][$cont]["y"] . " " . $data["pontos"][$cont]["z"] . ", " );
                else
                    $str .= ($data["pontos"][$cont]["x"] . " " . $data["pontos"][$cont]["y"] . " " . $data["pontos"][$cont]["z"] );
            }
            
            $path = "tri_teste.json";
            $file = fopen($path, "r");
            $data="";
            while(!feof($file)){
                $data .= fread($file, filesize($path));
            }
            fclose($file);
            $data= json_decode($data, true);
            $str_tri="";
            for($cont=0; $cont < count($data["triangulos"]); $cont++){
                if($cont < count($data["triangulos"])-1)
                    $str_tri .= ($data["triangulos"][$cont]["tri_a"] . " " . $data["triangulos"][$cont]["tri_b"] . " " . $data["triangulos"][$cont]["tri_c"] . ", " );
                else
                    $str_tri .= ($data["triangulos"][$cont]["tri_a"] . " " . $data["triangulos"][$cont]["tri_b"] . " " . $data["triangulos"][$cont]["tri_c"] );
            }

            echo "
            <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
                                point='${str}'/>
                            <Viewpoint
                                position='0 0 10'
                                orientation=''
                                description='camera'/>
                        </IndexedTriangleSet>
                    </shape> 
                </scene> 
            </x3d>
            ";
        ?>

    </body> 
</html>

我的結論是:如果您使用 X3D,最好使用后端編程語言。

我不是 jQuery 方面的專家,但是通過快速查找,我認為您應該在 getJSON 之后嘗試.then() function,然后在代碼 then 的括號內編寫 rest 這個問題中使用了一個例子

此外,您可以使用此鏈接中指定的 the.done() 而不是.then()(您必須向下滾動一點才能查看 the.done() 示例)

另一種選擇是將您的 $("div").html() 添加到 getJson 回調 function 中,如下所示:

 $.getJSON("dados_teste.json", function(data) {
     //your current code
     //you $("div").html() code
 }

讓我知道這個答案是否有幫助:)

嘗試將一個任務的執行與另一個任務的開始計時,稱為race condition ,應該避免。 而是在收到變量后調用您的.html() 因為你有 2 個獨立的依賴進程創建變量,你可以在makeDiv() function 中檢查它們。

var str, str_tri
 $.getJSON("dados_teste.json", function(data) {
               ...
                str = str.slice(0, -2);
                makeDiv();
            });
 $.getJSON("tri_teste.json", function(data) {
               ...
                str_tri = str_tri.slice(0, -2);
                makeDiv();
            });


function makeDiv() {
 if (!str || !str_tri || str =='' || str_tri == '') return;
 $("div").html( `......`);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM