在这一部分我们写了一个小小的AJAX应用,它能够rate一些东西(译Keel注:就是对某些东西投票),就像在youtube.com上面看到的一样。
首先我们需要一些服务器端代码,这个例子中用到了一个PHP文件,读取rating参数然后返回rating总数和平均数。看一下rate.php代码.
虽然这些例子也可以不使用AJAX来实现,但显示我们不会那么做,我们用jQuery生成一个DIV容器,ID是"rating".
$(document).ready(function() {
// generate markup
var ratingMarkup = ["lease rate: "];
for(var i=1; i <= 5; i++) {
ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";
}
// add markup to container and applier click handlers to anchors
$("#rating").append( ratingMarkup.join('') ).find("a").click(function(e) {
e.preventDefault();
// send requests
$.post("rate.php", {rating: $(this).html()}, function(xml) {
// format result
var result = [
"Thanks for rating, current average: ",
$("average", xml).text(),
", number of votes: ",
$("count", xml).text()
];
// output result
$("#rating").html(result.join(''));
} );
});
});
$(function() {
var addClickHandlers = function() {
$("a.clickMeToLoadContent").click(function() {
$("#target").load(this.href, addClickHandlers);
});
};
addClickHandlers();
});
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
var handler = function(data) {
...
};
// add click handler and pass foobar!
$('a').click( function(event) { handler(foobar); } );
// if you need the context of the original handler, use apply:
$('a').click( function(event) { handler.apply(this, [foobar]); } );