jQuery getJSON()函数用法指南

2021年3月9日16:25:04 发表评论 634 次浏览

getJSON()方法在jQuery中, 使用GET HTTP请求从服务器获取JSON编码的数据。

语法如下:

$(selector).getJSON(url, data, success(data, status, xhr))

参数:此方法接受上述和以下所述的三个参数:

  • 网址:它是必填参数。它用于以请求的字符串形式指定URL。
  • 数据:它是一个可选参数, 用于指定将发送到服务器的数据。
  • 打回来:它也是一个可选参数, 在请求成功时运行。

返回值:它返回XMLHttpRequest对象。

下面的示例说明了jQuery中的getJSON()方法:

employee.json文件:

{"名称":" Tony Stark", "年龄":" 53", "角色":"技术内容作家", "公司":" Geeks for Geeks")

例子:本示例获取JSON文件并显示其内容。

<!DOCTYPE html>
<html>
  
<head>
     <title>
         jQuery getJSON() Method
     </title>
      
     <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </script>
      
     <!-- Script to get JSON file and display its content -->
     <script type = "text/javascript" language= "javascript" >
         $(document).ready( function () {
               
             $( "#fetch" ).click( function (event){
                 $.getJSON( 'employee.json' , function (emp) {
                     $( '#display' ).html( '<p> Name: ' + emp.name + '</p>' );
                     $( '#display' ).append( '<p>Age : ' + emp.age+ '</p>' );
                     $( '#display' ).append( '<p> Role: ' + emp.role+ '</p>' );
                     $( '#display' ).append( '<p> Company: ' + emp.company+ '</p>' );
                 });
             });
         });
       </script>
    </head>
       
    <body>
       <p>
           Click on the button to fetch employee data
       </p>
           
       <div id = "display" style = "background-color:#39B54A;" ></div>
           
       <input type = "button" id = "fetch" value = "Fetch Employee Data" />
        
    </body>
</html>

输出如下:

单击按钮之前:

在点击按钮之前

单击按钮后:

单击按钮后

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: