javascript - 将 jquery 数据发送到 struts Action

标签 javascript jquery ajax struts2

我想将数据从我的 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 序列化的某些属性,你可以使用结果 excludePropertiesincludeProperties 的参数。这两个参数是互斥的。

@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/

相关文章:

Javascript:对象的 this.var 在 jQuery 方法中

javascript - MDL 选项卡的 "Tab Rendered"事件

javascript - 使 jQuery ComboBox 的选项不可选择

javascript - 尽管由 ajax 加载,但 DOM 元素只是偶尔创建

javascript - 向 Rails Controller 发送 AJAX 请求,然后向外部服务发送 HTTParty,后者将 JSON 返回到 .html.erb 文件中的输出

javascript - 如何同步两个不同页面上的按钮?

javascript - 带有 Jquery 的 3 级相关下拉菜单

jquery - 日期选择器选定的值始终出现在第一个文本框中

javascript - 条形图 D3.js 错误 : Invalid value for <rect> attribute

javascript - 使用 JavaScript/JQuery 通过 AJAX 传递数组