我在Spring中使用Ajax。通過Ajax,我調用了一個控制器方法,在其中加載一個xml文件並解析它。我想將解析後的節點(Object)傳遞給html頁面作爲對Ajax調用的響應。在Spring中通過Ajax調用獲取節點對象
這是我的AJAX調用
$.ajax({
url: "query1",
type: "POST",
//dataType: "xml",
success: function(data) {
alert("in jax response");
alert("DATA" + data);
// parseXml(data);
}
});
這是我的控制器方法
@RequestMapping(value = "/query1", method = RequestMethod.POST)
public @ResponseBody Node executeQuery1(ModelMap model) throws ParserConfigurationException, SAXException,IOException, XPathExpressionException {
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
String filepath = "C:\\test.xml";
System.out.println("PATH: " + filepath);
doc = builder.parse(filepath);
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile("//person[@id=1]");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODE);
// Cast the result to a DOM NodeList
Node personNode = (Node) result;
model.addAttribute("xmlnode", personNode);
System.out.println("model set. going to return");
return personNode;
}
如果我返回一個字符串,而不是節點的,我得到的警報彈出。但是在返回節點對象時失敗。
另外我想用Javascript解析這個節點。所以,請讓我知道做到這一點的最佳方式。我應該將節點轉換爲XML字符串並返回XML字符串嗎?
簡單而明顯的方法是簡單地將XML以原始形式傳遞給服務器 - 您的意思是將XML以原始形式傳遞給客戶端?如果是,那麼這樣做是不可能的,因爲這樣做可以在客戶端查看整個XML。安全限制是存在的,因此需要在服務器端解析XML。 – rdp 2013-04-23 13:07:12