我正在研究新聞摘要器,它的一個要求是在使用從數據庫調用的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