jQuery get(),post(),ajaxStart(),ajaxStop()

时间:2009年07月04日作者:simaopig评论次数:24

用jQuery进行Ajax处理,get(),post()这两个函数使用率是相当高的。只是因为其简单高效,易理解,所以基本上大家都很看好它们。相信各位也一定看过gmail的效果,在内容成功加载之前,显示一个loading按钮,内容正确加载后,按钮消失。这是咋做的呢?稍候为大家介绍的ajaxStart()和ajaxStop()函数将为您揭晓谜底。

get():jQuery.get(url,[data],[callback],[type])

与之前介绍的getJSON()或是getScript()比,多了个参数type。这个参数的作用是“Ajax请求服务器端返回的内容格式,xml, html, script, json, text, _default”

通常get()函数只是简单地取得由URL指定的文件,然后将纯文本格式(指定格式)的数据提供给回调函数。但是如果在根据服务器提供的MIME类型知道响应的是XML的情况下,提供给回调函数的将是XML DOM树。

post():jQuery.post(url,[data],[callback],[type])

与get()的请求参数完全相同,二者的唯一区别就是,在向服务器端发送ajax请求时,给url传递的参数data是以get方式传送还是以post方式传送,一般我比较喜欢用post()函数。

ajaxStart():ajaxStart(callback),ajaxStop():ajaxStop(callback)

一个是当AJAX 请求开始时执行函数。绑定一个对象后,由该对象触发。另一个是当AJAX 请求结束时执行函数。一般与ajaxStart()成对出现,以提供某种效果。

下面我们用这四个函数来继续模拟“字典操作”,首先我们用get()函数来去请求XML文件。

<div class="letter" id="letter-d">
    <h3>D</h3>
    <div class="button">Load</div>        
</div>
<!-- 用css文件定义id为loading的div的样式为display:none -->
<div id="loading">
    Loading...
</div>
<div id="dictionary">
</div>

定义xml文件,稍候用get()方法,将xml的内容拼装在id为dictionary的div中

<?xml version="1.0" encoding="UTF-8"?>
<entries>
  <entry term="DANCE" part="v.i.">
    <definition>
      To leap about to the sound of tittering music, preferably with arms about your neighbor's wife or daughter.  There are many kinds of dances, but all those requiring the participation of the two sexes have two characteristics in common:  they are conspicuously innocent, and warmly loved by the vicious.
    </definition>
  </entry>
  <entry term="DAY" part="n.">
    <definition>
      A period of twenty-four hours, mostly misspent.  This period is divided into two parts, the day proper and the night, or day improper <![CDATA[&mdash;]]> the former devoted to sins of business, the latter consecrated to the other sort.  These two kinds of social activity overlap.
    </definition>
  </entry>
</entries>
$(document).ready(function() {
  // 字母D下面的按钮被点击时触发发函数
  $('#letter-d .button').click(function() {
    // 用get()方法加载d.xml,返回数据为data
    $.get('d.xml', function(data) {
      // 将id为dictionary的div里内容清空
      $('#dictionary').empty();
      // 循环处理每个entry标签里面的quote标签,并且这个quote标签得有author属性
      $(data).find('entry:has(quote[author])').each(function() {
        // 定义临时变量,可以entry为当前被循环的entry
        var $entry = $(this);
       
        // 拼装html
        var html = '<div class="entry">';
        html += '<h3 class="term">' + $entry.attr('term') + '</h3>';
        html += '<div class="part">' + $entry.attr('part') + '</div>';
        html += '<div class="definition">'
        // 在entry条目里面获取definition标签里的内容
        html += $entry.find('definition').text();
        // quote为quote标签里的内容
        var $quote = $entry.find('quote');
       
        // 如果quote不为空
        if ($quote.length) {
          html += '<div class="quote">';
          // 循环处理quote标签里的line标签的内容
          $quote.find('line').each(function() {
            html += '<div class="quote-line">' + $(this).text() + '</div>';
          });
          // 如果quote标签里面author属性的值不为空
          if ($quote.attr('author')) {
            html += '<div class="quote-author">' + $quote.attr('author') + '</div>';
          }
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';
        // 将id为dictionary里面的加上html的内容
        $('#dictionary').append($(html));
      });
    });
  });
});

下面我们再来用post()方法来进行ajax加载,这次我们使用服务器端语言php,将数据通过url,用post()方法将其发送至服务器端,最后获取请求

//服务器端代码e.php
<?php
$entries = array(
  'EDIBLE' => array(
    'part' => 'adj.',
    'definition' => 'Good to eat, and wholesome to digest, as
      a worm to a toad, a toad to a snake, a snake to a pig,
      a pig to a man, and a man to a worm.'
,
  ),
  'EDUCATION' => array(
    'part' => 'n.',
    'definition' => 'That which discloses to the wise and
      disguises from the foolish their lack of
      understanding.'
,
  )
);
if (isset($entries[strtoupper($_REQUEST['term'])])) {
  $entry = $entries[strtoupper($_REQUEST['term'])];
 
  $html = '同样是拼div里面要显示的真正内容,这里就不给出代码了';
 
  print($html);
?>

同样是拼要显示的代码,只不过这次是用php来完成的,再来看一下页面代码

<div class="letter" id="letter-e">
    <h3>E</h3>
    <ul>
        <li><a href="e.php?term=Eavesdrop">Eavesdrop</a></li>
        <li><a href="e.php?term=Edible">Edible</a></li>
    </ul>
</div>
<!-- 用css文件定义id为loading的div的样式为display:none -->
<div id="loading">
    Loading...
</div>
$(document).ready(function() {
  // 点击字母E下面的超链接时触发函数
   $('#letter-e a').click(function() {
     // 用post方法向e.php传递参数term,参数的值为超链接显示的text
     $.post('e.php', {'term': $(this).text()}, function(data) {
      // 将返回的数据直接放入id为dictionary的div中
       $('#dictionary').html(data);
     });
     // 禁止超链接默认的链接操作
     return false;
   });
});

另外,大家也都看到了,我这个代码里面是有loading的,在点击按钮的时候就会显示loading,有数据返回的时候就会消失这用的就是ajaxStart()和ajaxStop()方法。

$(document).ready(function() {
 // 将id为loading内容为Loading...的这段内容放置在id为dictionary的内容之前
 // 在有ajax发生前,将其显示出来
 // 在ajax结束后,将其隐藏掉
  $('<div id="loading">Loading...</div>')
    .insertBefore('#dictionary')
    .ajaxStart(function() {
      $(this).show();
    }).ajaxStop(function() {
      $(this).hide();
    });
});

声明: 本文采用 BY-NC-SA 协议进行授权 | 小小子
转载请注明转自《jQuery get(),post(),ajaxStart(),ajaxStop()

标签:,分类:JavaScript
23条评论
  1. 粥小卜留言于:2009年07月04日21:46

    介个是虾米界面啊!哈哈 演示看不懂哎 :evil:

    [回复]

  2. simaopig留言于:2009年07月04日21:49

    @粥小卜
    呃,这是我前一段套的一个页面,是一款网页游戏的登录页。
    里面登录那的代码用的是ajax,就随便拿过来了。呵呵。

    [回复]

  3. bolo留言于:2009年07月04日22:04

    360出网页游戏了?你有份制作吗?我到时捧场

    [回复]

  4. simaopig留言于:2009年07月04日22:07

    @bolo
    呵呵,与合作伙伴搞的。现在真正合作运营的有三款,还有几款马上要加入。
    我搞的是充值那块,主要负责和游戏方面的接口啥的。
    不过充值我也没有提成和奖金。哈哈。

    [回复]

  5. bolo留言于:2009年07月04日22:14

    @simaopig
    怪啊,360首页看不到游戏频道入口,居然要靠google :!: 这款商业大坑我玩过

    [回复]

  6. young001留言于:2009年07月04日22:18

    专业的啊,不懂的漂过

    [回复]

  7. simaopig留言于:2009年07月04日22:18

    @bolo
    呵呵,首页确实没有做入口,目前好像只在安全卫士和保险箱上面有推荐吧。

    游戏中心

    商业大亨这款游戏目前好像还很火,不过没有“武林英雄”推荐的猛。

    [回复]

  8. simaopig留言于:2009年07月04日22:19

    @young001
    没事啊。到时候向你请教Linux的问题。呵。

    [回复]

  9. 小明猪留言于:2009年07月05日09:34

    之前也试着用AJAX做这个效果,失败了 :cry: 一些函数不知道是啥意思,话说四毛猪看的这本书是什么?

    [回复]

  10. simaopig留言于:2009年07月05日09:53

    @小明猪
    《jQuery基础教程》,去年买的一本书呢,一直也没看,呵呵。

    [回复]

  11. 小明猪留言于:2009年07月05日10:03

    @simaopig
    记下来,准备看 :oops:

    [回复]

  12. LAONB留言于:2009年07月05日12:28

    这个不错,慢慢跟你学。
    顺便说下,代码框要是再宽点就好了 :arrow:

    [回复]

  13. simaopig留言于:2009年07月05日15:01

    @小明猪
    呵呵。。希望对你有用。呵。

    [回复]

  14. simaopig留言于:2009年07月05日15:01

    @LAONB
    呵,不错的建议,这就去调整一下。

    [回复]

  15. LAONB留言于:2009年07月05日22:15

    @simaopig
    现在看着舒服多了, :roll: 充分利用页面的宽度 :D

    [回复]

  16. simaopig留言于:2009年07月05日22:20

    @LAONB
    呵呵,以前想过改,不过忘了。就是感觉看页面有些不舒服。呵呵。 :D

    [回复]

  17. 看海留言于:2009年07月06日10:49

    全局的ajaxStart 和stop 怎么定义的.我看JQUERY的API上写的是$(“#loading”).ajaxStart(function(){
    //….
    })

    [回复]

  18. 看海留言于:2009年07月06日12:37

    研究下全局的ajaxStart stop怎么用的吧。哈哈。研究完告诉我。

    就是不管在哪只要是调用JQUERY 的AJAX方法都会调用ajaxStart stop方法。

    这样我就不用每个AJAX都去写AJAXSTART了

    [回复]

  19. simaopig留言于:2009年07月06日12:55

    @看海
    只要放入在$(document).ready({});这里就是全局的了啊。

    然后你不总得有个对象来显示嘛。ajaxStart和ajaxStop本来就是全局的。嗯。

    [回复]

  20. alswl留言于:2010年04月28日17:28

    请教一下,左下角的 更多关于 “jquery …” 的结果,是哪个插件实现的?

    [回复]

发表评论

*

*