有一个基于 Java 的 Web 应用程序,其中包含一个页面,其中的帖子提要是在 JSTL 的帮助下动态生成的。用户目前可以">喜欢"提要中的任何帖子,但事实证明,使用 AJAX 实现起来要困难得多。我知道我在这里真的很接近,但无法弄清楚出了什么问题。
它有效,但仅适用于数组中的第一项。因此,在源中按下的任何"赞"按钮只会更新源中的第一个"赞"按钮。为什么动态分配的div 值(输入名称=likesDivCount(只注册第一个赋值?
索引.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
看起来您有多个具有相同 ID 的表单:"#likesform"。这是因为您的表单是在循环中生成的。
我建议您删除 ID,将其替换为 css 类(或其他东西(并重写 JS 以搜索目标表单中的元素,例如:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
一旦你有了有效的html,就会更容易排除故障