我想将数据从我的 javascript 发送到我的 struts 操作。这只是一个 id,因此我想知道是否有比通过 form.submit(); 更好的方法;
这是我要发送的变量。
var id = $('[data-detailsid="' + $(this).data('headid') + '"]');
正确的做法是什么?
我当前的 js 函数:
$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id
});
还有我的 struts Action :
@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;
}
}
最佳答案
如果您通过 Ajax 调用操作,则无需返回 dispatcher
结果。如果您在 classpash 上有 json 插件并且对操作进行了 @ParentPackage("json-default")
注释,则可以返回结果类型 json
。您可以使用 json 结果的 root
参数来定义执行结果时被序列化的对象。默认情况下,root
设置为操作实例,因此所有属性都被序列化。如果你想限制/允许 json 序列化的某些属性,你可以使用结果 excludeProperties
和 includeProperties
的参数。这两个参数是互斥的。
@Result(type="json", params = {"includeProperties", "productId" })
如果它被填充到操作 bean 并且操作类有一个 getter 方法,它将返回 productId
到页面。
您可以使用成功回调函数获取结果
$.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 );
});
关于javascript - 将 jquery 数据发送到 struts Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35563808/