CS 4385 - Topics in Software Engineering

星期二, 9月 20, 2005

XMLHttpRequest

Dynamic HTML and XML: The XMLHttpRequest Object

From previous post. We use JSON as a medium to transfer data or function.
XHttpRequest is a protocal and interface to transmit JSON.

Example

Sending Request
function loadXMLDoc(url) {
...
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
req.send("");

}

}
Receive response
function processReqChange() {
if (req.readyState == 4) {
if (req.status == 200) {
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);

}

}

}
Display response message
function showDetail(evt) {
evt = (evt) ? evt : ((window.event) ? window.event : null);
var items, content, div;
if (evt) {
var select = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
loadXMLDoc(select.value);
items = req.responseXML.selectNodes("//item");
content = items(0).text;
div = document.getElementById("details");
div.innerHTML = "";
div.innerHTML = content;

}

}

From the above example, the reponse XML can be JSON data

<item>
{"menu": {
"id": "file",
"value": "File:",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
</item>

Notice, there is a IE cache issue. When duplicated request is made, IE will ignore new request by response the cached result.
To enforce IE to get the leastest reponse. The following code may be use.
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
but when i using this. items = req.responseXML.selectNodes("//item"); will get nothing return.

0 Comments:

發佈留言

<< Home