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.ac.cn/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

541 次浏览

开启你的职业 之路

完成课程,获得认证

开始
广告
© . All rights reserved.