eponymous
eponymous

Reputation: 2228

How to send request parameters by Ajax to Struts2 action class

I have a Struts2 web application consisting of the following files:

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

I want to send the strings "aaa" and "bbb" by Ajax to controller.ControllerSln#editProfile() method. How can I achieve it?

Upvotes: 0

Views: 5715

Answers (2)

xrcwrn
xrcwrn

Reputation: 5337

Give the complete javascript ajax call code if it is simle 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();
            }
        }

}

Upvotes: 0

Sedat KURT
Sedat KURT

Reputation: 502

Your ControllerSln has String attributes which are called str1 and str2.Also their getter and setter must be created by eclipse automaticly. After that , your action has to be like this : http://localhost:8080/project/editprofile.action?str1="+str1+"&str2="+str2; When your action starts,struts will match parameters because their names are the same.. You can see print str1 and str2 on your editProfile() method.

Upvotes: 1

Related Questions