如何通过Ajax将请求参数发送到Struts2动作类

时间:2013-01-06 01:28:05

标签: javascript ajax jsp struts2

我有一个包含以下文件的Struts2 Web应用程序:

member.jsp

<script type="text/javascript">    
    String str1 = "aaa";
    String str2 = "bbb";

    xmlhttp.open("GET", "http://localhost:8080/project/editprofile.action", true);
    xmlhttp.send(null); 
</script> 

struts.xml

<action name="editprofile" method="editProfile" class="controller.ControllerSln">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStream</param>
    </result>
</action>  

ControllerSln.java

public String editProfile() throws UnsupportedEncodingException {
    return SUCCESS;
} 

我想通过Ajax将字符串“aaa”和“bbb”发送到controller.ControllerSln#editProfile()方法。我怎样才能实现它?

2 个答案:

答案 0 :(得分:1)

你的ControllerSln有String属性,叫做str1和str2.Al所以它们的getter和setter必须由eclipse自动创建。 在那之后,你的行动必须是这样的: http:// localhost:8080 / project / editprofile.action?str1 =“+ str1 +”&amp; str2 =“+ str2; 当您的操作开始时,struts将匹配参数,因为它们的名称相同。 您可以在editProfile()方法上看到print str1和str2。

答案 1 :(得分:0)

如果它是simle javascript

,请提供完整的javascript ajax调用代码
<script type="text/javascript">
        function updateProfile()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (typeof xmlhttp == "undefined")
            {
                ContentDiv.innerHTML="<h1>XMLHttp cannot be created!</h1>";
            }

            else{

                var str1 = "aaa";
                var str2 = "bbb";

                var str='?str1='+str1+'&str2='+str2;
                var query='editProfile'+str;
//str1 and str2 should be there at Controller.ControllerSln to fetch data from ajax 
                xmlhttp.open("GET",query,true);
                xmlhttp.onreadystatechange=function()
                {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        document.getElementById("UpdatedProfile").innerHTML=xmlhttp.responseText;
                        //UpdatedProfile  div where u want to display result of ajax
                    }
                }

                xmlhttp.send();
            }
        }

}

相关问题