2013-04-23 34 views
0

我在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字符串嗎?

回答

0

您可以使用JSON格式來返回您的對象。例如Jackson JSON API,您可以將對象轉換爲JSON格式並作爲字符串返回。或者,如果您想使用XML,請將您的Node對象轉換爲XML表示形式並返回爲String。使用XML作爲字符串,您需要相應地在AJAX代碼中解析它。

0

(我以前的版本假設你將XML從客戶端傳遞到服務器)。

您無法按原樣傳遞DOM節點。它不會使用toString方法進行序列化。

要傳遞DOM子樹,您需要將其解壓縮回XML。在"Writing Out a DOM as an XML File"上的Java教程頁面有一個例子,它幾乎完成了你想要做的事情。查找標題「寫出DOM的子樹」。 (唯一的區別是你的代碼使用XPath而不是DOM API來定位你想要的節點。)

或者,你可以通過遍歷DOM樹來「手動序列化」你的節點,將內容提取到新的-DOM)對象,然後序列化那些......不知何故。例如,你可以構造JSONObject/JSONArray實例,然後序列化爲JSON。您在客戶端獲得的內容不會是XML。 (這可能是件好事。)

+0

簡單而明顯的方法是簡單地將XML以原始形式傳遞給服務器 - 您的意思是將XML以原始形式傳遞給客戶端?如果是,那麼這樣做是不可能的,因爲這樣做可以在客戶端查看整個XML。安全限制是存在的,因此需要在服務器端解析XML。 – rdp 2013-04-23 13:07:12