我想将我的javascript中的数据发送到我的struts动作。它只是一个id,因此我想知道是否有更好的方法,而不是通过form.submit();
这是我要发送的变量。
var id = $('[data-detailsid="' + $(this).data('headid') + '"]');
这样做的正确方法是什么?
我当前的js功能:
$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id
});
我的struts行动:
@Action("/deleteProduct")
@ResultPath("/")
@Result(name = "success", location = "jsp/board.jsp")
public class DeleteAction {
int productId;
@Autowired
private UserDao userDao;
public String execute() {
Product currentProduct = new Product();
currentProduct.setId(productId);
userDao.deleteProduct(currentProduct);
setProducts(userDao.getProducts());
return "success";
}
public void setProductId(int productId) {
this.productId = productId;
}
}
答案 0 :(得分:4)
如果您通过Ajax调用操作,则无需返回dispatcher
结果。如果您在classpash上有json插件并且对该操作有json
注释,则可以返回结果类型@ParentPackage("json-default")
。您可以对json结果使用root
参数来定义执行结果时序列化的对象。默认情况下,root
设置为操作实例,因此所有属性都已序列化。如果要限制/允许json序列化中的某些属性,可以使用参数excludeProperties
和includeProperties
。两个参数都是互斥的。
@Result(type="json", params = {"includeProperties", "productId" })
如果将productId
填充到操作bean并且操作类具有getter方法,它将返回到页面。
您可以使用
获取成功回调函数的结果$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id,
dataType: "json"
}).done(function(data){
console.log("The product id:" + data.productId);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});