如何使用 jQuery 加载 JSON 数据?

jqueryweb developmentfront end technology

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

以下是此方法使用的所有参数的说明

  • url:包含请求发送到的 URL 的字符串
  • data:此可选参数表示将发送到服务器的键/值对。
  • callback:此可选参数表示数据成功加载后要执行的函数。

将您的 JSON 内容添加到 `result.json` 文件中

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

以下代码片段展示了此方法的用法。它链接到上面创建的 result.json 文件。

示例

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

相关文章