简体   繁体   中英

How to post and receive data in a loop using AJAX to and from a servlet

I am working on a news summarizer and one of its requirements is to display a list of article titles dynamically on a webpage using AJAX called from a database. I have been able to successfully configure the datastore(google app engine) and use the AJAX call to display article title. However, there is one big issue here. I am only able to call and show a single title. I want to run the AJAX call inside a loop so that I can display 10 news articles stored in datastore from 1 to 10 using the variable i of the loop as the unique reference.

The AJAX CODE :

         function change(element) {
            var xmlhttp;
            var i = 1;
            var param = "category=" + element + "&no=" + i; // This i is the key to my operation. 
            alert(param); //testing purpose
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                //alert('function()');
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var div = document.getElementById('content');
                    div.innerHTML = '';
                    for (i = 1; i <=10; i++) {

                        var a = document.createElement('a');
                        a.href = "#";
                        a.onclick = rem.bind(null, i); 
                        a.innerHTML = '<h2 id="theading'+i+'">'
                                + xmlhttp.responseText + '</h2>'; //the title will go here.

                        div.appendChild(a);
                        div.appendChild(document.createElement('br'));
                    }
                } 

            }

            xmlhttp.open("POST", "/display?" + param, true);
            xmlhttp.send();
}

I also request to suggest JavaScript code and not jquery, as I am unfamiliar with it. These are my humble beginnings.

UPDATE

MY SERVLET CODE:

    public class ArticleHandler extends HttpServlet {
        public void service(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
            resp.setContentType("text/html");

            PrintWriter out = resp.getWriter();

            String category=req.getParameter("category");
            String number=req.getParameter("no");
            int i = Integer.parseInt(number);       
            List<EntityArticles> articles =    RegisterClass.ofy().load().type(EntityArticles.class).filter("category ",category).list();

            out.write(articles); // Is this the correct way to send this list articles ?


        }
    }

Is this the correct way to send the list ?

10 articles in responseText, you can render html in server code to responseText(loop in server code). And then in ajax sucess you call

         var div = document.getElementById('content');
            div.innerHTML = xmlhttp.responseText;

I have created a fiddel for you to understand check it. Ajax Example in fiddle

Are you doing post request or get request? I'm asking this because I saw method as "POST" and parameter passed as "GET" by putting it in url. Please correct that part too in your code.

loadXMLDoc=function()
{
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","/ahmadfaizalbh/LaH8F/show/",true);
xmlhttp.send();
}

The best choice is to call the ajax one time and get 10 items.

But, if you have no alternative, you can modify the function a little:

function change(element, i){
    var xmlhttp;
    //var i=1;
    var param = "category=" + element + "&no=" + i;
    ...
}

Call the function this way (10 times as you need):

for(i=1;int <= 10; i++){
    change(element, i);
}

UPDATE To make one time the ajax call, you can do:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    //append html node
    //the object is xmlhttp.responseText. The loop will depend if this is json, html objects, string, etc
}
xmlhttp.open("POST", "/display?" + param, true);
xmlhttp.send();

To obtain 10 results you need (necessarily) to modify the server side script or servlet. If you cannot have access to modify the servlet, is impossible to get 10 items in a single ajax call.

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