Reputation: 2796
I am using Tomcat 7 Java Servlets in the backend of my web app. The issue that I am facing is that when I perform an HTTP GET Request using jQuery Ajax,the HttpServletResponse always returns the HTML body of the calling page, instead of returning the required data.
jQuery code:
function perform_ajax(view_name) {
$(function() {
var url = 'get-view-data-by-view-name';
$.ajax({
method: 'GET',
data: {view_name: JSON.stringify(view_name)},
beforeSend: function() {
alert(view_name);
},
success: function(data) {
alert(data);
//console.log(data);
},
error: function(xhr) {
alert("Error: asdasd");
}
});
});
}
Servlet code:
public void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String x = req.getParameter("view_name");
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(x);
}
Even if I replace the lastt line of my Servlet code with:
resp.getWriter().write("aaaa");
commenting out everything else in the doGet function, the Servlet still returns the Html body of the calling page.
I have been stuck on this for several hours now. Went through scores of SO questions, tried various things like using a different MIME type such as plain, but all I get in response is the Html code of the caller page. Please help me find where I am going wrong and resolve this issue.
Upvotes: 0
Views: 1586
Reputation: 2796
I forgot to pass the url in the ajax function call; dont know how I could miss that out!
function perform_ajax(view_name) {
$(function() {
var url = 'get-view-data-by-view-name';
$.ajax({
url: url, // + Added URL to ajax call
method: 'GET',
data: {view_name: JSON.stringify(view_name)},
beforeSend: function() {
alert(view_name);
},
success: function(data) {
alert(data);
//console.log(data);
},
error: function(xhr) {
alert("Error: asdasd");
}
});
});
}
Upvotes: 1
Reputation: 71
Check header, that return get request. It must have application/json. But browser may be interpreted text as html.
Use curl for checking work.
And returns JSON object instead of a string, for example:
...
response.setContentType("application/json");
String x = req.getParameter("view_name");
PrintWriter out = response.getWriter();
JSONObject obj = new JSONObject();
obj.put("view_name", x);
out.print(obj);
...
Upvotes: 0