Search

12/10/2007

How to make Ajax work for you

How to make Ajax work for you » SlideShare - simple & clear AJAX codes
How to make Ajax work for you

var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText);
} else {
alert('Error code ' + xhr.status);
}
}
};
xhr.open('GET', '/helloworld.txt', true);
xhr.send(null);

function createXHR() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
return xhr;
}

var xhr = createXHR();
xhr.onreadystatechange = onComplete;
xhr.open('POST', '/helloworld.php', true);
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.send('name=Simon&age=26');

xhr.open('POST', '/helloworld.php', true);
The third argument specifies that we want to make an asynchronous request (“tell me when you’re done by calling this function”). If you set this to false you’ll get a synchronous request, which will completely hang the browser until the request returns. Don’t do that.

function buildQueryString(obj) {
var bits = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
bits[bits.length] = escape(key) + '=' +
escape(obj[key]);
}
}
return bits.join('&');
}
var s = buildQueryString({
name: 'Simon',
age: 26
});
name=Simon&age=26

There's still a complete doRequest function. Keep reading ...
<form id="evil" action="http://example.com/admin/delete.php" method="POST">
<input type="hidden" name="id" value="5">
</form>
<script>
document.getElementById('evil').submit()
</script>

沒有留言: