如何在 jQuery 中使用 jQuery.getJSON 載入 JSON 檔案?


jQuery.getJSON( url, [data], [callback] ) 方法使用 GET HTTP 請求從伺服器載入 JSON 資料。

假設我們在 result.json 檔案中有以下 JSON 內容 −

{
"name": "Amy",
"age" : "24",
"sex": "female"
}

示例

以下程式碼片段顯示了此方法的用法 −

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               $.getJSON('result.json', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.name + '</p>');
                  $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                  $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
               });
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage" style = "background-color:#cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

更新日期:2020 年 2 月 17 日

900 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告