如何使用jQuery加载JSON数据?

要使用jQuery加载JSON数据,请使用getJSON()ajax()方法。jQuery.getJSON()方法使用GET HTTP请求从服务器加载JSON数据。

这是此方法使用的所有参数的描述-

  • url- 包含请求发送到的URL的字符串

  • 数据 -此可选参数表示将发送到服务器的键/值对。

  • callback- 此可选参数表示每当成功加载数据时将执行的函数。

result.json文件中添加JSON内容-

{
"name": "Amit",
"age" : "27",
"sex": "male"
}

以下是显示此方法用法的代码段。它将上面创建的result.json 文件链接起来,

示例

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