如何使用jQuery.getJSON在jQuery中加载JSON文件?

jQuery.getJSON(url,[data],[callback])方法使用GET HTTP请求从服务器加载JSON数据。

假设我们在result.json文件中具有以下JSON内容-

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

示例

以下是显示此方法用法的代码片段-

   <head>
      <script src = "https://cdn.staticfile.org/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>