通过 Ajax 调用使用 Struts 2 的 HTTP 数组参数 [英] HTTP Array Parameters with Struts 2 via an Ajax Call

查看:42
本文介绍了通过 Ajax 调用使用 Struts 2 的 HTTP 数组参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将数组参数发送到 Struts 2 操作类时遇到问题.我正在使用 struts 2.1.8.1.

I'm having an issue sending array parameters to a Struts 2 action class. I am using struts 2.1.8.1.

下面是一些示例代码:

public class MyAction extends ActionSupport {

    private String[] types;

    public String execute() {
        return SUCCESS;
    }

    public String[] getTypes() {
        return types;
    }

    public void setTypes(String[] types) {
        this.types = types;
    }
}

问题是通过jquery ajax方法发送数组时:

The problem is when sending an array via the jquery ajax method:

$.ajax({
    type: 'POST',
    url: 'Myaction.action',
    data: {
        types: ["this", "is", "a", "test"]
    }
});

导致异常发生:

ognl.ParseException: 在第 1 行第 7 列遇到"]" "] "".

如何使用 jQuery 将数组发送到我的 Struts2 动作类?我需要包含类似于拦截器的东西吗?或者 jQuery 中有一个选项可以删除它吗?

How can I use jQuery to send the array to my Struts2 action class? Is there something along the lines of an interceptor that I need to include? Or is there an option in jQuery to remove this?

我在使用 jQuery UI 可排序控件时也遇到了这个问题,但我使用正则表达式删除了[]"字符解决了这个问题.我想避免这种情况,因为那个解决方案让我很困扰.我想我可以自己构建字符串,而不是使用对象表示法,但除非你能说服我,否则我想使用对象表示法.

I also encountered this problem with the jQuery UI Sortable control, but I solved that using a regex to remove the "[]" characters. I would like to avoid that, because that solution bothers me. I suppose I could just build the string myself, instead of using the object notation, but unless you can convince me otherwise, I would like to use the object notation instead.

推荐答案

IIRC Struts 不喜欢 jQuery 1.4+ 格式,不过你可以使用传统格式,只要把它放在你的 $.ajax() 调用:

IIRC Struts doesn't like the jQuery 1.4+ format, you can use the traditional format though, just put this any time before your $.ajax() call:

$.ajaxSettings.traditional = true; 

您可以在 $.param() 文档,最好的说明是他们的简短示例:

You can read more about the 1.4+ default vs traditional serialization in the $.param() documentation, the best illustration is their short example:

// <=1.3.2: (traditional in 1.4+)
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4: (default in 1.4+)
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"

这篇关于通过 Ajax 调用使用 Struts 2 的 HTTP 数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆