今天些AJAX程序时,出了个小问题,想利用xsl显示返回的xml,但是每当调用js的transformNode时总出错,
提示 "所需要的数据还没有准备好"
当时我以为时requestObj(XHR对象)的readyState还没完成,但是在这之前已经有了对readyState的判断,于是错误
定位在docStyle这里,经检查样式文件没问题,最后锁定为transformNode执行的时候 doc 还没有把数据加载完全.
var doc = new ActiveXObject("MSXML2.DOMDocument.3.0");
doc.loadXML(requestObj.responseText);
var docStyle = new ActiveXObject("MSXML2.DOMDocument.3.0");
docStyle.load("data.xslt");
doc.transformNode(docStyle); //这里出错
doc.loadXML(requestObj.responseText);
var docStyle = new ActiveXObject("MSXML2.DOMDocument.3.0");
docStyle.load("data.xslt");
doc.transformNode(docStyle); //这里出错
后来发现dom也有个onreadystatechange和readySate属性,不过我用了另外一个方法
用了一个叫自由线程的对象,感觉有点像异步.
虽然麻烦,不过其好处是可以往xsl里加参数
1 var docStyle = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
2 docStyle.async = false;
3 docStyle.load("data.xslt");
4
5 var docTemplate = new ActiveXObject("MSXML2.XSLTemplate");
6 docTemplate.stylesheet = docStyle;
7
8 var processor = docTemplate.createProcessor();
9
10 processor.input = doc;
processor.addParameter("index", "2");//加参数
11 processor.transform();
12 var res = processor.output;
13 divContent.innerHTML = res;
2 docStyle.async = false;
3 docStyle.load("data.xslt");
4
5 var docTemplate = new ActiveXObject("MSXML2.XSLTemplate");
6 docTemplate.stylesheet = docStyle;
7
8 var processor = docTemplate.createProcessor();
9
10 processor.input = doc;
processor.addParameter("index", "2");//加参数
11 processor.transform();
12 var res = processor.output;
13 divContent.innerHTML = res;