Reputation: 4418
I have an Ajax request coming from client side after a key press. The servlet returns a string.
How should I grab this string on the client side? It should be split on ","
on the client side and display the list. We are using Velocity for rendering the HTML.
Servlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
SomeDAO dao = new SomeDAO();
ArrayList<String> results = dao.acResults(acInfo);
StringBuilder sb = new StringBuilder();
int count = 0;
for (String acResult : results) {
sb.append(acResult);
count++;
if (count == results.size()) {
break;
}
sb.append(',');
}
out.println(sb);
out.close();
}
Upvotes: 2
Views: 9197
Reputation: 1474
If you are not using Jquery then you can use following:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","YOUR_SERVLET_RELATIVE_URL",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
Upvotes: 0
Reputation: 20803
Sounds like a simple jQuery ajax response scenario - can't you handle the response with code of following nature ?
var responseText = '';
$.ajax({ type: "GET",
url: "/YourServletURL",
success : function(text)
{
responseText = text;
}
});
//alert response or process it or display somewhere
alert(responseText);
Upvotes: -1
Reputation: 980
Dont use "async: false" or it will lose all the AJAX meaning. Do all the stuff you want in the success method. To split by ',', just use split() and to easily iterate arrays use $.each()
$.ajax({ type: "GET",
url: "/YourServletURL",
success : function(text)
{
var list = text.split(',');
$.each(list, function(index, value) {
alert(index + ': ' + value);
});
// This will show the values. Change "alert" for $('div#mydiv').html(value) or so
}
});
Upvotes: 2