如何使用 jQuery Ajax 将 javascript 数组发送到 struts 动作

2022-01-16 00:00:00 type-conversion jquery ajax java struts2

我是 Struts 2 的新手.我想通过使用 jQuery AJAX 请求将 javascript 数组发送到 Struts 操作类.
警报工作正常, execute() 不工作.
当我将 System.out.println("language : "+ language); 放入 execute() 方法时,输出为

I am new to Struts 2. I want to send a javascript array to a Struts action class by using jQuery AJAX request.
The alert is working fine, the execute() is not working.
When I put System.out.println("language : "+ language); in the execute() method, the output is

语言:null.

var langArr = [];
    $("#language").each(function()
    {
      var selectedLang = $("select").val();
      var selectedValues = $(this).val();
      langArr.push(selectedValues);
     });
    alert("Languages : " + langArr);

    $.ajax({
        method: "POST",
        url: "getProjectPost",
        data: { "language" : langArr },
        dataType : "json",
        traditional: true,
        success:
            function()
            {
             alert("Success");
            },
        error: 
           function()
            {
             alert("Error");
            }
    });

这是我的动作课

public class ProjectPostAction {

    private int[] language;

    public final int[] getLanguage() {
        return language;
    }

    public final void setLanguage(int[] language) {
        this.language = language;
    }

    public String execute() throws Exception {          
           System.out.println("language : "+ language[0]);
           return "success";    
    }

推荐答案

Jquery 使用 $.param 在内部使用 $.ajax.

Jquery serializes data sent as parameters using $.param internally when doing ajax request with $.ajax.

数据应设置为整数数组或以逗号分隔的整数列表的字符串,以便 jQuery 可以在与请求一起发送之前正确序列化它.

The data should be set as array of integers or string with comma separated list of integers, so jQuery can correctly serialize it before sending with the request.

您只能使用 traditional 设置向 struts2 发送数组参数,因为 struts 使用类型转换来使用键作为参数名称来填充操作的属性.

You can send an array parameter to struts2 only with traditional setting because struts using type conversion to populate a property of the action using keys as parameter names.

因此,该数组应该是一个原始整数数组,但您的数组包含其他不是原始整数的对象.

为了演示你可以看这个demo来了解如何获取参数值并以与 $.ajax 相同的方式对其进行序列化.

To demonstrate you can see this demo to understand how to get parameter values and serialize it the same way like is doing $.ajax.

Struts2 还可以通过默认类型转换来转换包含逗号分隔值的字符串.例如,您可以看到复选框列表值如何传递给 struts 操作.

Struts2 also can convert a string containing a comma separated values by default type conversion. For example you can see how checkbox list values are passed to struts action.

相关文章