jQuery.getJSON() 方法如何載入 jQuery 中的 JSON 資料?


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

以下是該方法使用所有引數的說明 -

  • url - 包含傳送請求的 URL 的字串
  • data - 此可選引數表示將傳送到伺服器的關鍵/值對。
  • callback - 此可選引數表示在成功載入資料時要執行的函式。

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

{
  "name": "David",
  "age" : "25",
  "sex": "male"
}

以下是顯示此方法用法的程式碼片段 -

示例

   <head>
      <title>The jQuery Example</title>
      <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>
   
</html>

更新於:17-2-2020

536 瀏覽量

啟動您的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.