开发者

Save a form in an XML file using Ajax and JSP

I want to create a simple form with a name and an email and save these data in an XML file. So far I found that using Ajax with jQuery is quite easy. So I used the usual code:

//dataString have the values taken from the form
var dataString = 'name='+ name + '&email=' + email;
$.ajax({
 type: "POST",
 url: "users.xml",
 data: dataString,
 dataType: "xml",
 success: function() { .... }
});

If I understood wel开发者_如何学编程l, in the url I should add the name of the XML file that will be created.

When the user clicks a button I call the function with the Ajax request, and then I should call somewhere a function for generating the xml.

I am using also two beans. One is for setting the elements of the user and the other is for saving the data in the XML. I am using the XStream library for the xml although I don't know if is the best solution.

The problem now it that I can not connect all these together in order to save the data in the XML.

Does anyone know what should I do?

Thanks a lot!


Sorry, but your understanding is incorrect. The url should point to the URL of a server-side CGI/API which processes the HTTP POST request. The dataType indicates the data type of the HTTP response which is been returned from the server side after processing the HTTP request. This can be either a HTML string, a JSON string or a XML string. To ease immediate processing of the response, you can set the datatype there so that jQuery knows how to "preformat" the response. Often JSON is been used since it's the most compact and the quickiest to process in Javascript.

In case of a JSP/Servlet application, you need to let the url point to a Servlet which has the doPost() method implemented like follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // First process HTTP request.
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    // Do your business stuff here. You want to store this in a xml file? 

    // Then return HTTP response.
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write("<status>ok</status>"); // Or whatever XML string you would like to return depending on the outcome of the business stuff.
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜