开发者

How to send a XML doc to server from client in jQuery

I'm trying to send XML doc to server from client. But when server get a XML doc. It's always empty. Here is my jquery function. It's send XML to server:

var str = '<?xml version="1.0" encoding="UTF-8"?><foo><bar>Hello World</bar></foo>';
    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);
        }
    });

And server side code. It's recieve a xml doc.

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

Can you guys put some working example? And thank you for any advice and post.


You are missing the "type" property in your ajax request. The default value if you don't provide it is GET.

Also there's no need to convert your data to XML Dom when you are sending it over the wire, unless you want to do something with it on client side:

     function sendXml()   {  
        var str = '<?xml version="1.0" encoding="UTF-8"?><foo><bar>Hello World</bar></foo>';
        // 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);
   }
 });


Besides the point of missing the type in your ajax request. Have you tried simply using

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

This would be the simplest way to access the "data" parameter from the post request.

As from the JavaDoc, getInputStream is to be used with binary data; to handle text data use getReader(), which returns a bufferedReader to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜