简体   繁体   中英

Return data to ajax from java Servlet method doGet

I have my function ajax like this :

$.ajax({
        url: "associer_type_flux", // It's  my servlet
        dataType : "xml",
        type : "GET",
        data : { },
        success: function(response){
            alert("fine");
        },
        error:  function(data, status, er){
            alert(data+"_"+status+"_"+er);
        }
    });

And my method doGet in my servlet like this :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String forward = ""; 
    try {           
        String fluxXML = "";
        ServicesCodeTypeFluxGlobaux servicesCodeTypeFluxGlobaux = new ServicesCodeTypeFluxGlobauxImpl();

            fluxXML = "<lescodetypeflux>";

            fluxXML += "</lescodetypeflux>";
            PrintWriter printWriter  = response.getWriter();
            printWriter.println(fluxXML);

        }
        forward = "/associerCode/accueil_association.jsp";
        getServletContext().getRequestDispatcher(forward).forward(request, response);           
    }
    catch (Exception e) {
        forward = "/erreur.jsp";
        request.setAttribute("msg", e.getMessage());
    }       
}

So my problem is that, I cant get data in my jsp .. But i don't know how get this data or return this data from doGet method .. Now I have an alert Error ..

Thx

A few suggestion to make it work -

  1. don't forget to set mime type in your case "text/xml" or "application/xml"

  2. You can not use both together out.println() and requestdispatcher as it will throw exception. out.println() will print the value in response body but request dispatcher will redirect you to some other page and incase of ajax what you will get is the whole content of the page where you redirected.

so in your case you should only use out.println()

So your final code should look like this -

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/xml");
    String forward = ""; 
    try {           
        String fluxXML = "";
        ServicesCodeTypeFluxGlobaux servicesCodeTypeFluxGlobaux = new ServicesCodeTypeFluxGlobauxImpl();

            fluxXML = "<lescodetypeflux>";

            fluxXML += "</lescodetypeflux>";
            PrintWriter printWriter  = response.getWriter();
            printWriter.println(fluxXML);
            printWriter.close();
        }        
    }
    catch (Exception e) {
        //print xml with error value
    }       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM