<<High Performance JavaScript>>读书笔记-7.Ajax

Data Transmission

Requesting Data

There are five general techniques for requesting data from a server:

• XMLHttpRequest (XHR)

var url = '/data.php';

var params = [

'id=934875',

'limit=20'

];

var req = new XMLHttpRequest();

req.onreadystatechange = function() {

if (req.readyState === 4) {

var responseHeaders =req.getAllResponseHeaders(); // Get the response headers.

var data = req.responseText; // Get the data.

// Process the data here...

}

}

req.open('GET', url + '?' + params.join('&'), true);

req.setRequestHeader('X-Requested-With','XMLHttpRequest'); // Set a request header.

req.send(null); // Send the request.

 

• Dynamic script tag insertion

var scriptElement = document.createElement('script');

scriptElement.src = 'http://any-domain.com/javascript/lib.js';

document.getElementsByTagName('head')[0].appendChild(scriptElement);

 

var scriptElement = document.createElement('script');

scriptElement.src = 'http://any-domain.com/javascript/lib.js';

document.getElementsByTagName('head')[0].appendChild(scriptElement);

function jsonCallback(jsonString) {

var data = eval('(' + jsonString + ')');

// Process the data here...

}

 

• iframes

• Comet

• Multipart XHR

var req = new XMLHttpRequest();

req.open('GET', 'rollup_images.php', true);

req.onreadystatechange = function() {

if (req.readyState == 4) {

splitImages(req.responseText);

}

};

req.send(null);

 

// Read the images and convert them into base64 encoded strings.

$images = array('kitten.jpg', 'sunset.jpg', 'baby.jpg');

foreach ($images as $image) {

$image_fh = fopen($image, 'r');

$image_data = fread($image_fh, filesize($image));

fclose($image_fh);

$payloads[] = base64_encode($image_data);

}

// Roll up those strings into one long string and output it.

$newline = chr(1); // This character won't appear naturally in anybase64 string.

echo implode($newline, $payloads);

 

function splitImages(imageString) {

var imageData =imageString.split("\u0001");

var imageElement;

for (var i = 0, len = imageData.length; i < len;i++) {

imageElement = document.createElement('img');

imageElement.src = 'data:image/jpeg;base64,' +imageData[i];

document.getElementById('container').appendChild(imageElement);

}

}

 

function handleImageData(data, mimeType) {

var img = document.createElement('img');

img.src = 'data:' + mimeType + ';base64,' + data;

return img;

}

 

function handleCss(data) {

var style = document.createElement('style');

style.type = 'text/css';

var node = document.createTextNode(data);

style.appendChild(node);

document.getElementsByTagName('head')[0].appendChild(style);

}

 

function handleJavaScript(data) {

eval(data);

}

 

var req = new XMLHttpRequest();

var getLatestPacketInterval, lastLength = 0;

req.open('GET', 'rollup_images.php', true);

req.onreadystatechange = readyStateHandler;

req.send(null);

function readyStateHandler{

if (req.readyState === 3 &&getLatestPacketInterval === null) {

// Start polling.

getLatestPacketInterval =window.setInterval(function() {

getLatestPacket();

}, 15);

}

if (req.readyState === 4) {

// Stop polling.

clearInterval(getLatestPacketInterval);

// Get the last packet.

getLatestPacket();

}

}

 

function getLatestPacket() {

var length = req.responseText.length;

var packet = req.responseText.substring(lastLength,length);

processPacket(packet);

lastLength = length;

}

 

Sending Data

1.XMLHttpRequest

var url = '/data.php';

var params = [

'id=934875',

'limit=20'

];

function xhrPost(url, params, callback) {

var req = new XMLHttpRequest();

req.onerror = function() {

setTimeout(function() {

xhrPost(url, params, callback);

}, 1000);

};

req.onreadystatechange = function() {

if (req.readyState == 4) {

if (callback && typeof callback ==='function') {

callback();

}

}

};

req.open('POST', url, true);

req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

req.setRequestHeader('Content-Length',params.length);

req.send(params.join('&'));

}

 

2.Beacons

var url = '/status_tracker.php';

var params = [

'step=2',

'time=1248027314'

];

(new Image()).src = url + '?' + params.join('&');

 

Data Formats

1.XML

2.JSON

3.HTML

4.Custom Formatting

Format

Size

 Download time

Parse time

Total load time

Verbose XML

 582,960 bytes

 999.4 ms

 343.1 ms

 1342.5 ms

Verbose JSON-P

 487,913 bytes

 598.2 ms

 0.0 ms

 598.2 ms

Simple XML

437,960 bytes

 475.1 ms

83.1 ms

558.2 ms

Verbose JSON

487,895 bytes

 527.7 ms

 26.7 ms

554.4 ms

Simple JSON

 392,895 bytes

 498.7 ms

29.0 ms

 527.7 ms

Simple JSON-P

 392,913 bytes

 454.0 ms

3.1 ms

457.1 ms

Array JSON

 292,895 bytes

305.4 ms

 18.6 ms

 324.0 ms

Array JSON-P

292,912 bytes

 316.0 ms

 3.4 ms

319.4 ms

Custom Format (script insertion)

 222,912 bytes

 66.3 ms

11.7 ms

78.0 ms

Custom Format (XHR)

222,892 bytes

 63.1 ms

14.5 ms

 77.6 ms

http://techfoolery.com/formats/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值