[英]Return data to ajax from java Servlet method doGet
我有這樣的功能ajax:
$.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);
}
});
我的方法doGet在我的servlet中是這樣的:
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());
}
}
所以我的問題是,我無法在jsp中獲取數據..但是我不知道如何從doGet方法獲取此數據或返回此數據..現在我有一個警報Error ..
謝謝
一些使其可行的建議-
不要忘記在您的情況下為“ text / xml”或“ application / xml”設置mime類型
您不能同時使用out.println()和requestdispatcher,因為它將引發異常。 out.println()將在響應正文中打印該值,但請求分派器會將您重定向到其他頁面,如果使用ajax,您將獲得的是重定向頁面的整個內容。
所以在你的情況下,你應該只使用out.println()
因此您的最終代碼應如下所示-
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.