25 April 2006
This post may be outdated due to it was written on 2006. The links may be broken. The code may be not working anymore. Leave comments if needed.
老板要求 Ajax 的 reponse 是 XML, 所以要找一个解析 xml 的 javascript 库。
因为已经用了 JSAN , 所以就在那找了个 XML.ObjTree
我用 XML::Writer 来构造 xml response. 比如说我们的 response 为
<xml><message>OK</message></xml>
然后 javascript 的代码大概为:
function ajax() {
var myAjax = new Ajax.Request( url, {
method: 'get',
parameters: pars,
onSuccess: showResponse,
} );
}
function showResponse(request) {
response = request.responseText;

JSAN.use('XML.ObjTree');
var xotree = new XML.ObjTree();
var tree = xotree.parseXML( response );

$('message').innerHTML = tree.xml.message;
}
这是针对回复只有一个 <message> 的。如果是多个 messages, javascript 的代码可以为:
for (i = 0; i < tree.xml.message.length; i++) {
唯一有点麻烦的是,我们期待回复的是 message array, 但是只有回了一个 message, 那这个 for 会失败,但是有 tree.xml.message 所以在 for 后面得加个
// ugly hack, for only one
if (tree.xml.message) {

Have fun!


blog comments powered by Disqus