【问题标题】:Send jquery data to struts action将 jquery 数据发送到 struts 动作
【发布时间】:2016-02-22 21:04:47
【问题描述】:

我想将数据从我的 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;
        }
}

【问题讨论】:

  • 使用$.ajax向服务器发送数据
  • 感谢@charlietfl 我正在尝试让 ajax 工作,但我不太习惯。介意看看我做了什么?我编辑了我的帖子。我想在我的操作中将我的 productId 设置为我的 javascript 中的 id 变量
  • $.ajax 中的基本信息是正确的。使用成功和错误处理程序进行确认。我对struts一无所知...只需将ajax数据视为<input>name="productId的表单提交
  • 我会试一试,让你知道。但是 ajax 似乎非常强大。我的页面不必重新加载即可获取数据神圣的钼 :')
  • 作为 RomanC 答案的集成,任何操作结果都将始终在成功回调 (.done()) 内结束,即使您返回 ERROR,因为 jQuery 对操作结果一无所知,它使用 HTTP 代码来检测响应的状态,并且调度程序的结果将始终为 200。要输入错误回调 (.fail()),您需要返回带有 errorcode 参数的 json 结果或 httpheader 结果,如herehere 所述

标签: javascript jquery ajax struts2


【解决方案1】:

如果您通过 Ajax 调用操作,则无需返回 dispatcher 结果。如果您在 classpash 上有 json 插件并且对操作有 @ParentPackage("json-default") 注释,则可以返回结果类型 json。您可以在 json 结果中使用root 参数来定义执行结果时要序列化的对象。默认情况下,root 设置为操作实例,因此所有属性都被序列化。如果您想限制/允许 json 序列化中的某些属性,您可以对结果 excludePropertiesincludeProperties 使用参数。这两个参数是互斥的。

@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 );
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 2012-01-09
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2022-01-04
    • 2013-10-24
    • 2013-01-31
    相关资源
    最近更新 更多