tutorials:getting started with jquery---3...
时间:2010-08-18 来源:oneGeng
RATE ME: USING AJAX
在这个部分,我们将要编写一个小Ajax程序,它可以帮助用户来引用一些东西,就像youtube.com做的那样。
我们需要一些服务器端的代码。这个例子需要一个php文件,它的作用的读取'rating"参数,返回ratings的数量以及平局闹的rating。闲看一下rate.php这个文件。
虽然没有Ajax这个例子也能工作,但是我们并不希望那样做,因此我们需要用jQuery生成必要的标记,为div增加一个ID"rating"。
$(document).ready(function() {
// generate markup
$("#rating").append("Please rate: ");
for ( var i = 1; i <= 5; i++ )
$("#rating").append("<a href='#'>" + i + "</a> ");
// add markup to container and apply click handlers to anchors
$("#rating a").click(function(e){
// stop normal link click
e.preventDefault();
// send request
$.post("rate.php", {rating: $(this).html()}, function(xml) {
// format and output result
$("#rating").html(
"Thanks for rating, current average: " +
$("average", xml).text() +
", number of votes: " +
$("count", xml).text()
);
});
});
});
这个代码片段生成了5个anchor元素,并把它们添加到"rating"的容器内。然后,为容器中的每一个anchor添加一个点击的处理器。当点击事件被触发的时候,一个post请求会被发送到rate.php,其中把anchor的内容作为参数。这个请求返回了一个xml,并且它会替代容器内的anchor。
如果你没有可供PHP运行的web服务器的话,那么你可以看一下在线的例子online example。这里还提供了一个没有使用JavaScript的例子,访问softonic.de,然后点击"Kurz bewerten!"。
关于jQuery更多关于Ajax的文档,你可以在Ajax Documentation或者Visual jQuery的Ajax下面找到。
使用Ajax一个常见的问题是:当你增加处理器的时候同时也要考虑被装载的文档,你需要在文档的内容装载完成后再应用这些处理器。为了防止书写重复的代码,你可以通过代理来完成:
function addClickHandlers() {
$("a.remote", this).click(function() {
$("#target").load(this.href, addClickHandlers);
});
}
$(document).ready(addClickHandlers);
现在当DOM准备好的时候addClickHandlers只被调用一次,然后每次用户通过class remote点击链接,内容就会被加载。
请注意$("a.remote", this),这个作为上下文。对于文档中的ready事件,this指的是整个文档,因此它会搜索整个文档来查找带class的名字为remote的ahchor。当通过load()对addClickHandlers进行回调的时候,this又指向一个不同的元素:在这个例子中,指的是带id的元素。 这就有效的组织了点击事件会不断的应用到同一链接上,最后造成崩溃。
另外一个关于回调的问题就是参数。你可能已经指定了一个回调,但是需要传递额外的参数。最简单的方式就是把回调包装在另外一个function里面:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
function handler(data) {
//...
}
// add click handler and pass foobar!
$('a').click(function(){
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function(){
handler.apply(this, [foobar]);
});
通过Ajax,这个例子就包含了很多web2.0的信息。现在我们看到了一些基础的Ajax,现在让我增加了更加新鲜的玩意。
可能感兴趣的链接:
- jQuery Ajax Documentation
- jQuery API - Contains description and examples for append and all other jQuery methods
- ThickBox - A jQuery plugin that uses jQuery to enhance the famous lightbox
ANIMATE ME: USING EFFECTS
通过show()和hide()可以添加动态的图片:
$(document).ready(function(){
$("a").toggle(function(){
$(".stuff").hide('slow');
},function(){
$(".stuff").show('fast');
});
});
你可以通过animate()来增加任何的动态效果,例如利用滑块增加渐变的效果:
$(document).ready(function(){
$("a").toggle(function(){
$(".stuff").animate({
},function(){
$(".stuff").animate({
});
});
要想看到更多炫的效果,你可以访问interface plugin collection。这个网站提供例子和文档。Interface是jQuery插件排在最靠前的位置,当然还有许多其他的东西。下一部分将会展示如何是用tablesorter插件。
可能感兴趣的链接:
- jQuery Effects Documentation
- Interface plugin










