1-4 使用get()方法以GET方式从服务器获取数据
本节编程练习不计算学习进度,请电脑登录imooc.com操作

使用get()方法以GET方式从服务器获取数据

使用get()方法时,采用GET方式向服务器请求数据,并通过方法中回调函数的参数返回请求的数据,它的调用格式如下:

$.get(url,[callback])

参数url为服务器请求地址,可选项callback参数为请求成功后执行的回调函数。

例如,当点击“加载”按钮时,调用get()方法向服务器中的一个.php文件以GET方式请求数据,并将返回的数据内容显示在页面中,如下图所示:

在浏览器中显示的效果:

从图中可以看出,通过$.get()方法向服务器成功请求数据后,在回调函数中通过data参数传回请求的数据,并以data.name格式访问数据中各项的内容。

任务

我来试试,亲自使用$.get()方法请求服务器中的数据

在下列代码的第23行,使用$.get()方法,请求服务器中 http://www.imooc.com/data/info_f.php 文件中的数据,并将返回的内容显示在页面中。

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>使用get()方法以GET方式从服务器获取数据</title>
  5. <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
  6. <link href="style.css" rel="stylesheet" type="text/css" />
  7. </head>
  8. <body>
  9. <div id="divtest">
  10. <div class="title">
  11. <span class="fl">我的个人资料</span>
  12. <span class="fr">
  13. <input id="btnShow" type="button" value="加载" />
  14. </span>
  15. </div>
  16. <ul></ul>
  17. </div>
  18.  
  19. <script type="text/javascript">
  20. $(function () {
  21. $("#btnShow").bind("click", function () {
  22. var $this = $(this);
  23. ? {
  24. $this.attr("disabled", "true");
  25. $("ul").append("<li>我的名字叫:" + data.name + "</li>");
  26. $("ul").append("<li>男朋友对我说:" + data.say + "</li>");
  27. }, "json");
  28. })
  29. });
  30. </script>
  31. </body>
  32. </html>
  1. #divtest
  2. {
  3. width: 282px;
  4. }
  5. #divtest .title
  6. {
  7. padding: 8px;
  8. background-color:blue;
  9. color:#fff;
  10. height: 23px;
  11. line-height: 23px;
  12. font-size: 15px;
  13. font-weight: bold;
  14. }
  15. ul
  16. {
  17. float: left;
  18. width: 280px;
  19. padding: 5px 0px;
  20. margin: 0px;
  21. font-size: 14px;
  22. list-style-type: none;
  23. }
  24. ul li
  25. {
  26. float: left;
  27. width: 280px;
  28. height: 23px;
  29. line-height: 23px;
  30. padding: 3px 8px;
  31. }
  32. .fl
  33. {
  34. float: left;
  35. }
  36. .fr
  37. {
  38. float: right;
  39. }
下一节