Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

java - Calling an action using Ajax URL in Struts 2

I am trying to connect to my action class by using URL as below in Ajax. But its not going into my action class and even it is not showing the selected value by using $("#selectedCountry").val().

function getstates(){           
    alert($("#selectedCountry").val());         
    $.ajax({
      type : "GET",
      url  : "/ThirdTask/selectstate.action",
      dataType : 'text',
      data : "name="+$("#selectedCountry").val(),
      success : function(){
        $('statesdivid').html();
      },
      error : alert("No values found..!!")
    });         
}

My JSP code as follows:

<s:select  name="selectedCountry"  list="{'india','china'}"  onclick="getstates();"/></div>
<div id="statesdivid">
<s:if test="%{#request.selectedstatenames != null}"> 
<s:select list="#request.selectedstatenames" name="selectedState">
</s:select>
</s:if>
</div>

My struts.xml:

<action name="selectstate.action" class="com.thirdtask.actions.SelectAction" method="selectstate">
 <result name="success">selecttag.jsp</result> 
</action>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To map an action to the method you should do something like

<action name="selectstate" class="com.thirdtask.actions.SelectAction" method="selectstate">
  <result>/selecttag.jsp</result> 
</action>

action name should be without action extension and result by default is named "success", the path to JSP should be absolute here.

Calling ajax

$.ajax({
    type : "GET",
    url  : "<s:url action='selectstate'/>",
    dataType : 'text/javascript',
    data : {'name' : $("#selectedCountry").text()},
    success : function(result){
      if (result != null && result.length > 0){
        $("statesdivid").html(result);
      }
    },
    error : function(xhr, errmsg) {alert("No values found..!!");}
});         

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...