if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/XML');
http_request.onreadystatechange = function(){
// do the thing
};
http_request.open('GET', 'http://www.example.org/some.file', true);
http_request.send(null);
name=value&anothername=othervalue&so=on
http_request.onreadystatechange = nameOfTheFunction;
我們來看看這個函數的功能是什麼.首先函數會檢查請求的狀態.如果狀態值是4,就意味著一個完整的服務器響應已經收到了,您將可以處理該響應.if (http_request.readyState == 4) {
// everything is good, the response is received
} else {
// still not ready
}
if (http_request.status == 200) {
// perfect!
} else {
// there was a problem with the request,
// for example the response may be a 404 (Not Found)
// or 500 (Internal Server Error) response codes
}
http_request.responseText – 以文本字符串的方式返回服務器的響應
http_request.responseXML – 以XMLDocument對象方式返回響應.處理XMLDocument對象可以用JavaScript DOM函數
<script type="text/Javascript" language="Javascript">
var http_request = false;
function makeRequest(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/XML');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
</script>
<span
style="cursor: pointer; text-decoration: underline"
>
Make a request
</span>
<?XML version="1.0" ?>
<root>
I'm a test.
</root>
...
>
...
var xmldoc = http_request.responseXML;
var root_node = XMLdoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);