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

How to send request parameters by Ajax to Struts2 action class

本文关键字:参数 Struts2 动作类 请求 何通过 Ajax      更新时间:2023-09-26

我有一个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"answers"bbb"到controller.ControllerSln#editProfile()方法。我怎样才能实现它?

你的ControllerSln有字符串属性str1和str2。它们的getter和setter也必须由eclipse自动创建。之后,您的操作必须像这样:http://localhost:8080/project/editprofile.action?str1="+str1+"&str2="+str2;当您的操作开始时,struts将匹配参数,因为它们的名称相同。您可以在editProfile()方法上看到打印str1和str2。

给出完整的javascript ajax调用代码,如果是简单的javascript

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

}