如何在jQuery中从客户端向服务器发送XML文档

我正在尝试从客户端向服务器发送XML文档。 但是当服务器获得XML文档时。 它总是空的。 这是我的jquery函数。 它将XML发送到服务器:

var str = 'Hello World'; var xmlData = strToXml(str); // convert string to xml console.log($.isXMLDoc(xmlData)); // return true $.ajax({ url: 'foo.bar' , processData: false , data: xmlData , success: function(response){ console.log(response); } , error: function(response) { console.log(response); } }); 

和服务器端代码。 它收到了一个xml文档。

 try { HttpServletRequest request = ServletActionContext.getRequest(); InputStream is = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = ""; System.out.println(reader.read()); // return -1 while((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } 

你们能举一些工作的例子吗? 谢谢你的任何建议和post。

您缺少ajax请求中的“type”属性。 如果您不提供默认值,则为GET。

当您通过网络发送数据时,也无需将数据转换为XML Dom,除非您想在客户端对其执行某些操作:

  function sendXml() { var str = 'Hello World'; // var xmlData = strToXml(str); // no need for this unless you want to use it // on client side // console.log($.isXMLDoc(xmlData)); $.ajax({ url: 'test.jsp', processData: false, type: "POST", // type should be POST data: str, // send the string directly success: function(response){ alert(response); }, error: function(response) { alert(response); } }); } 
 $.ajax({ type: "POST", url: 'foo.bar', processData: false, data: xmlData, success: function(response){ console.log(response); }, error: function(response) { console.log(response); } }); 

除了缺少ajax请求中的类型之外。 你尝试过简单使用吗?

 String xmlData = request.getParameter("data"); 

这将是从post请求访问“data”参数的最简单方法。

从JavaDoc开始 ,getInputStream将与二进制数据一起使用; 处理文本数据使用getReader(),它返回一个bufferedReader给你。