如何使用jQuery Ajax将javascript数组发送到struts动作 [英] How to send javascript array to struts action by using jQuery Ajax

查看:126
本文介绍了如何使用jQuery Ajax将javascript数组发送到struts动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Struts 2的新手。我想通过使用jQuery AJAX请求将一个javascript数组发送到Struts动作类。


警报工作正常, execute()无效。


当我在中执行 System.out.println(language:+ language); 时()方法,输出

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.

您只能使用传统设置向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.

这篇关于如何使用jQuery Ajax将javascript数组发送到struts动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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