使用 Ajax 从 DataTable 中删除单行 [英] Removing a single row from DataTable using Ajax
问题描述
我有一个 JSF 视图,它在 Primefaces DataTable
中列出集合中的项目.最右边的列包含删除按钮.当一个删除按钮被点击时,它应该进行一个 Ajax 调用,从会话变量 Cart
中删除相应的项目并就地更新视图.我希望请求和视图更改尽可能小.
I have a JSF view that lists items in a collection in a Primefaces DataTable
. The rightmost columns contain remove buttons. When a remove button is clicked, it is supposed to make an Ajax call, remove the corresponding item from the session variable Cart
and update the view in-place. I would like the request and the view change to be as minimal as possible.
这是我为此目的所拥有的:
Here is what I have for this purpose:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Register user</title>
</h:head>
<h:body>
<f:view>
<h:form id="itemsForm">
<p:outputPanel id="items">
<p:dataTable value="#{cart.itemList}" var="item">
<p:column>
<f:facet name="header">
<h:outputText value="name" />
</f:facet>
<h:outputText value="#{item.product.description}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="quantity" />
</f:facet>
<h:outputText value="#{item.quantity}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="" />
</f:facet>
<p:commandButton icon="ui-icon-close" title="remove from cart">
<p:ajax listener="#{cart.removeItem}"
update="form:itemsForm"
process="@this" />
</p:commandButton>
</p:column>
<f:facet name="footer">
Total amount: ${cart.totalAmount}
</f:facet>
</p:dataTable>
</p:outputPanel>
</h:form>
</f:view>
</h:body>
</html>
相应地,我在Cart.java
public void removeItem() {
System.out.println("REMOVE REQUEST ARRIVED");
}
但是,当我单击删除按钮时,removeItem
方法甚至没有执行.所以我的问题是:
However, the removeItem
method isn't even executing when I click a remove button.
So my questions are:
1) 我的 Ajax 调用有什么问题?我应该对 XHTML 进行哪些更改?
1) What is wrong with my Ajax call? What changes should I make to my XHTML?
2) 如何处理removeItem
方法中的请求并返回响应?
2) How do I handle the request in the removeItem
method and return a response?
3) 如何更新显示 totalAmount 的 footer
?
3) How do I update the footer
, which displays the totalAmount?
推荐答案
您可以在 actionListener
中将 #{item}
作为方法调用的参数传递.
You can pass #{item}
as a parameter of your method call in the actionListener
.
您的 .xhtml 页面应如下所示:
Your .xhtml page should look like this:
<p:dataTable id="cartTable" value="#{cart.itemList}" var="item">
<p:column>
<f:facet name="header">
<h:outputText value="" />
</f:facet>
<p:commandButton icon="ui-icon-close" title="remove from cart"
actionListener="#{cart.removeItem(item)}" update="cartTable" />
</p:column>
</p:dataTable>
这是你的 ManagedBean
的 removeItem
方法:
And this is the method removeItem
of your ManagedBean
:
@ManagedBean
@ViewScoped
public class Cart {
private List<Item> itemList;
public void removeItem(Item item) {
itemList.remove(item);
}
}
这篇关于使用 Ajax 从 DataTable 中删除单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!