我正在研究新闻摘要器,它的一个要求是在使用从数据库调用的AJAX的网页上动态显示文章标题列表。我已经能够成功配置数据存储(谷歌应用程序引擎)并使用AJAX调用来显示文章标题。但是,这里有一个大问题。我只能打电话并显示一个标题。我想在循环中运行AJAX调用,以便可以使用循环的变量i作为唯一引用来显示10个存储在数据存储中的新闻文章,从1到10。如何使用AJAX发送和接收来自servlet的循环中的数据
Ajax代码:
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();
}
我还要求提出的JavaScript代码,而不是jQuery的,因为我不熟悉它。这些是我卑微的开始。
UPDATE
我的servlet代码:
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 ?
}
}
这是发送列表中选择正确的方式?
是否有理由做10个Ajax调用,而不是在一次调用中获得全部10篇文章? – anon
是的。其实我对AJAX和Javascript很陌生。我不知道如何在一次调用中获得10篇文章,然后将它们设置为HTML。任何帮助,将不胜感激。 –
返回来自服务器的文章标题列表,而不是仅返回一篇文章的标题 – anon