jquery trick shots free chapter

Được đăng lên bởi chromono
Số trang: 14 trang   |   Lượt xem: 837 lần   |   Lượt tải: 0 lần
AJAX is a fundamental building block for web apps. It allows you to send only the data that you need, saving
bandwidth and speeding things up, making your sites feel native-like. In this chapter I will show you a number
of tricks that you can use to enhance your applications and I'll explain a few of the new things that recent
jQuery versions introduced.


34. Display file sizes next to download links
Did you know that you can send a HEAD request with AJAX and get the size of a file without downloading it?
With jQuery this is very easy:

<a href="001.html" class="fetchSize">First Trickshot</a>
<a href="034.html" class="fetchSize">This Trickshot</a>
<a href="ball.png" class="fetchSize">Ball.png</a>


// Loop all .fetchSize links
// Issue an AJAX HEAD request for each one
var link = this;
type: 'HEAD',
url: link.href,
complete: function(xhr){
var size = humanize(xhr.getResponseHeader('Content-Length'));
// Append the filesize to each
$(link).append(' (' + size + ')');

function humanize(size){
var units = ['bytes','KB','MB','GB','TB','PB'];
var ord = Math.floor( Math.log(size) / Math.log(1024) );
ord = Math.min( Math.max(0,ord), units.length-1);
var s = Math.round((size / Math.pow(1024,ord))*100)/100;
return s + ' ' + units[ord];


This snippet places the size of the file in braces next to its name. The script issues a HEAD request, which only
returns the headers and not the actual content of the file, which means that these requests are fast and

First Trickshot (871 bytes)
This Trickshot (1.27 KB)
Ball.png (12.49 KB)

35. Simplify your Ajax calls with deferreds
Deferreds are a powerful tool. jQuery returns a new deferred object for every AJAX request, which makes them
easier to work with. Here is how you can use deferreds to make your code more readable:

// This is equivalent to passing a callback as the
// second argument (executed on success):

Requesting a file that does not exist. This will trigger
the failure response. To handle it, you would normally have to
use the full $.ajax method and pass it as a failure callback,
but with deferreds you can can simply use the fail method:

console.log('Oops! The file is missing!');

As you will see in tip #55, deferreds have a lot of power behind them.


36. Run multiple AJAX requests in parall...
Để xem tài liệu đầy đủ. Xin vui lòng
jquery trick shots free chapter - Người đăng: chromono
5 Tài liệu rất hay! Được đăng lên bởi - 1 giờ trước Đúng là cái mình đang tìm. Rất hay và bổ ích. Cảm ơn bạn!
14 Vietnamese
jquery trick shots free chapter 9 10 718