jquery中的全局事件

ajaxStart(callback):Ajax请求开始时触发该事件

ajaxSend(callback):Ajax请求发送前触发该事件

ajaxSuccess(callback):Ajax请求成功时触发该事件

ajaxComplete(callback):Ajax请求完成时触发该事件

ajaxStop(callback):Ajax请求结束时触发该事件

ajaxError(callback):Ajax请求出现错误时触发该事件

 

可以对 jQuery 对象调用上述全局事件。

例如,当用户点击页面上某一按钮请求数据时,在页面上显示 loading... ,页面加载完成后隐藏

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>AjaxStartAjaxStop</title>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    $("#loading").hide();

    $("#loading").ajaxStart(function(){
        $(this).show();
    });

    $("#loading").ajaxStop(function(){
        $(this).hide();
    });

    $("button[name='btnLoad']").click(function(){    
        $.get("http://www.sohu.com", null, function(data){
            $("#content").text(data);
        });
    });    
});
</script>
<style type="text/css">
body{ padding:20px; }
textarea{ width:350px; height:120px; }
#loading{ background-color:#eee; border:solid 1px #999; margin:5px 0 10px; padding:5px; font-size:13px; }
</style>
</head>

<body>

<div id="loading">Loading.....</div>
<textarea id="content"></textarea>
<button name="btnLoad">Load</button>

</body>
</html>

 直接利用$.ajaxSetup(options)方法统一设定所有$.ajax()方法中的参数。代码如下:

$.ajaxSetup({        //统一设置$.ajax()方法中的相同部分
type: "GET",
 //data: "user="+escape($("#user").val())+"&comment="+escape($("#comment").val()),
 beforeSend:function(){$("#target").html("<img src='loading.gif' /><br>正在载入…");}, 
 error:function(){$("#target").html("<p>载入失败</p>");},
 success: function(data){     //第3个参数,回调函数,在请求完成后执行
    $("#target").html(data);
 }
});

 

 

也可以在ajax()里面直接使用;

function Ajax(){  
    $.ajax({
        type: "GET",
        url: "9-15.php",
        data: "user="+escape($("#user").val())+"&comment="+escape($("#comment").val()),   //escape()方法会将参数中的字符串编码成Unicode格式的字符串
        beforeSend:function(){            //发送请求之前
            $("#target").html("<img src='loading.gif' /><br>正在载入…");}, 
        error:function(){$("#target").html("<p>载入失败</p>");},
        success: function(data){         //请求成功时
            $("#target").html(data);
        }
    });
}

9-15.php                                                                         

header("Content-type: text/html; charset=gb2312"); 
$user=unescape($_GET['user']);
$comment=unescape($_GET['comment']);
for($i=1;$i<10000000;$i++);        //用于延时,以看到正在载入的图标
echo "<h3>评论人:".$user."</h3>";
echo "<p>内容:".$comment."</p>"
posted @ 2016-01-08 11:07  小军的代码库  阅读(843)  评论(0编辑  收藏  举报