生活在远方

是的,因为真正的生活是在远方

【jQuery】示例2:显示一个“Loading”提示

Written By: tr - Dec• 02•08

今天完成了一个在进行耗时长久的操作时,为了不让用户感到无聊而显示一个“载入中,请稍安勿躁”之类提示的小例子。

演示地址:此处

==============

为了使这个“耗时长久”的操作显得真实一些,我决定让我的jQuery通过ajax去调用一个PHP文件,并从PHP文件那里返回一些东西。当然,这只是一个demo,PHP文件不用太复杂:

$t=rand(3,6);
sleep($t);
$arr=array("t"=>$t, "foo"=>"bar");
$jarr=json_encode($arr);
echo $jarr;

值得注意的有两点:

第一,在返回到jQuery之前,我先用PHP函数json_encode将要返回的东西进行JSON编码。JSON是很通用的编码规范,jQuery、PHP都支持;

第二,返回需要用到的不是return,而是echo。这个很特别。我开始用的是return,然后在jQuery中死活得不到返回的数据流。

核心的jQuery代码是:

	var time_elapsed;
	var action;
$(document).ready(
 
	function()
	{
		$("a").filter("#long").click(
			function(event)
			{
				event.preventDefault();
				$.getJSON("ajaxcall.php", function(json)
					{
						time_elapsed=json.t;
						action=json.foo;
					}
				);
			}
		);
 
		$("div").filter("#div01").ajaxStart(
			function()
			{
				$(this).slideDown("slow");
			}
		).ajaxComplete(
			function()
			{
				alert("本次"+action+"的操作耗时"+time_elapsed+"秒。");
				$(this).fadeOut("slow");
			}
		);
	}
);

这里需要注意三点:

第一,变量的说明要在所有函数体之外,类似全局变量。虽然使用全局变量不好,但是在这样小规模的代码段中,也是可以接受的;

第二,请注意获得json数据流中变量的方法。由于在PHP中我是用JSON编码我的返回值,所以我必须用getJSON去调用PHP文件,从而获得数据。同时,可以注意到,经由getJSON得到的数据已经变成了一个对象数组,我可以用json.t,json.foo这样很直观的方法来获取返回值。

第三,请注意ajax调用和针对ajax调用时状态处理函数的声明。ajax的调用必须用$.getJSON的方式;而ajax调用状态中最重要的就是ajaxStart和ajaxComplete。

So far, so good.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">