如何修改此 JavaScript 程式碼以從 JSON 檔案中獲取影像 URL,並在 HTML 中顯示它?


這可以透過使用 JavaScript 方法JSON.parse()來解析 JSON 檔案並提取所需影像的 URL 來實現。然後,可以使用源屬性設定為此 URL 的 HTML img 標籤建立。最後,可以將此 img 標籤附加到現有的 HTML 元素以將其顯示在頁面上。

這需要一些基本的 JavaScript 語法知識,以及熟悉 JSON 在其中的結構和解析方式。掌握這些技能後,您應該能夠輕鬆地修改程式碼以實現您的目標!

讓我們深入瞭解文章,以便更好地理解如何修改 JavaScript 程式碼以從 Json 檔案中獲取影像 URL,並在 HTML 中顯示它。

使用 JSON.parse()

靜態方法JSON.parse()透過解析 JSON 字串建立 JavaScript 值或物件。在返回結果物件之前,可以使用可選的 reviver 函式應用轉換。

語法

以下是JSON.parse()的語法:

JSON.parse(text)
JSON.parse(text, reviver)

示例

考慮以下示例,其中我們使用JSON.parse(),執行指令碼並顯示影像。

<!DOCTYPE html>
<html>
   <body>
      <div id="tutorial"></div>
      <script>
         json_data = '{"icon_url": "https://tutorialspoint.tw/images/logo.png"}';
         json_data = JSON.parse(json_data);
         var getimage = document.createElement("img");
         getimage.onload = function() {
            document.getElementById("tutorial").appendChild(getimage);
         }
         getimage.src = json_data.icon_url;
      </script>
   </body>
</html>

當指令碼執行時,它將生成一個輸出,其中包含透過使用JSON.parse()顯示在網頁上的影像。

示例

執行以下指令碼並觀察我們將如何使用JSON.parse()來顯示網頁上的影像。

<!DOCTYPE html>
<html>
   <body>
      <button id="button" >click</button>
      <img id="tutorial">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script>
         $("#button").on("click",function(){
            var json='{"status":200,"count":1,"data":[{"image":"https://tutorialspoint.tw/images/logo.png"}]}';
            var obj = jQuery.parseJSON(json);
            imagedata = obj.data[0].image;
            if (imagedata == ""){
            $( "#tutorial" ).attr('src', "imageerror.jpg");
            } else {
               $( "#tutorial" ).attr('src', imagedata);
            }
         });
      </script>
   </body>
</html>

執行上述指令碼後,輸出視窗將彈出,在網頁上顯示點選按鈕。當用戶點選按鈕時,事件被觸發並在網頁上顯示影像。

示例

在以下示例中,我們執行指令碼,獲取影像 URL,並使其出現在網頁上。

<!DOCTYPE html>
<html>
   <body>
      <div id="tutorial"></div>
      <script>
         var data = {
            "images": [{
               "image1": "https://tutorialspoint.tw/images/logo.png"
            }, {
               "image1": "https://tutorialspoint.tw/static/images/logo-color.png"
            }, {
               "image1": "https://tutorialspoint.tw/html/images/html-mini-logo.jpg"
            }, ]
         };
         data.images.forEach(function(obj) {
            var image = new Image();
            image.src = obj.image1;
            document.getElementById("tutorial").appendChild(image);
         })
      </script>
   </body>
</html>

當指令碼執行時,它將生成一個輸出,其中包含顯示在網頁上的影像。

更新於: 2023年4月20日

8K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告