简体   繁体   中英

How should I get the Ajax response from the servlet?

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();
}

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
     }
});

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>

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);

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