jquery异步请求实例
1、用ajax
jsp代码如下:
$.ajax({type:"get",dataType:"json",url:"<%=basePath%>actionSmUser.do?method=getUserMsgByUserId",data:"userid="+userId,success:function(msg){vardata=eval("("+msg.responseText+")");alert($("#userName").val());$("#userName").val(data[0].userName);}});
2、用getJSON方式:
$.getJSON(url,function(data){if(data!=null&&data!=""){$("#userIdInput").val(data[0].userId);$("#userNameInput").val(data[0].userName);$("#menusIdInput").val(data[0].menusId);$("#depIdInput").val(data[0].depId);$("#isValidInput").val(data[0].isValid);$("#userIdInput").attr("disabled",true);}});两种台Action返回字符串的组织形式可采用JSONArrayarray的方式,返回array.toJSONString();
本文是要做一个二级联动,动态的。通过jquery返回json类型的数据,然后在jsp页面处理,生成第二级下拉列表菜单。
所需js库:jquery.js,json2.js
jar包:json-lib-2.2.3-jdk15.jar,ezmorph-1.0.6.jar
Java代码
<%@pagecontentType="text/html;charset=UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<scripttype="text/javascript"src="jquery.js"></script>
<scripttype="text/javascript"src="json2.js"></script>
<scripttype="text/javascript">
jQuery(function($){
varobj=$("#category");
if(typeofobj!='undefined'&&obj!=''){
showGongdanType(obj.val());
}
});
functiononchangeShow(category){
jQuery.ajax({
url:"${contextPath}/assets/statistic/ajaxGetType.do",
data:{statCategory:category},//传递参数
type:"post",
cache:false,
dataType:"json",
success:onchangecallback
});
}
functiononchangecallback(data){
document.all['type'].options.length=0;
varstr="<optionvalue=''>全部</option>";
for(vari=0;i<data.length;i++){
str+="<optionvalue='"+data[i].value+"'>"+data[i].valueName+"</option>"
}
$("#type").html(str);
}
functionshowGongdanType(category){
jQuery.ajax({
url:"${contextPath}/assets/statistic/ajaxGetType.do",
data:{statCategory:category},
type:"post",
cache:false,
dataType:"json",
success:callback
});
}
functioncallback(data){
document.all['type'].options.length=0;
varstr="<optionvalue=''>全部</option>";
for(vari=0;i<data.length;i++){
str+="<optionvalue='"+data[i].value+"'>"+data[i].valueName+"</option>"
}
$("#type").html(str);
//下面代码是为了第二级下拉列表的定位。因为非struts2的标签,无法自己定位
if("${gongdanType}"!=''){
for(vari=0;i<data.length;i++){
if(data[i].value=="${gongdanType}")
document.all['type'].selectedIndex=i+1;
}
}
}
</script>
<tdwidth="10%"height="25"class="alignLeft">
统计类别:
</td>
<tdwidth="10%"valign="top"class="alignLeft">
<s:selectname="form.category"list="categorys"id="category"
listKey="value"listValue="valueName"
onchange="onchangeShow(this.value)">
</s:select>
</td>
<tdwidth="10%"height="25"class="alignLeft">
工单类型:
</td>
<tdwidth="10%"valign="top"class="alignLeft">
<selectname="form.gongdanType"id="type">
</select></td>
<%@pagecontentType="text/html;charset=UTF-8"%><%@taglibprefix="s"uri="/struts-tags"%><scripttype="text/javascript"src="jquery.js"></script><scripttype="text/javascript"src="json2.js"></script><scripttype="text/javascript">jQuery(function($){varobj=$("#category");if(typeofobj!='undefined'&&obj!=''){showGongdanType(obj.val());}});functiononchangeShow(category){jQuery.ajax({url:"${contextPath}/assets/statistic/ajaxGetType.do",data:{statCategory:category},//传递参数type:"post",cache:false,dataType:"json",success:onchangecallback});}functiononchangecallback(data){document.all['type'].options.length=0;varstr="<optionvalue=''>全部</option>";for(vari=0;i<data.length;i++){str+="<optionvalue='"+data[i].value+"'>"+data[i].valueName+"</option>"}$("#type").html(str);}functionshowGongdanType(category){jQuery.ajax({url:"${contextPath}/assets/statistic/ajaxGetType.do",data:{statCategory:category},type:"post",cache:false,dataType:"json",success:callback});}functioncallback(data){document.all['type'].options.length=0;varstr="<optionvalue=''>全部</option>";for(vari=0;i<data.length;i++){str+="<optionvalue='"+data[i].value+"'>"+data[i].valueName+"</option>"}$("#type").html(str);//下面代码是为了第二级下拉列表的定位。因为非struts2的标签,无法自己定位if("${gongdanType}"!=''){for(vari=0;i<data.length;i++){if(data[i].value=="${gongdanType}")document.all['type'].selectedIndex=i+1;}}}</script><tdwidth="10%"height="25"class="alignLeft">统计类别:</td><tdwidth="10%"valign="top"class="alignLeft"><s:selectname="form.category"list="categorys"id="category"listKey="value"listValue="valueName"onchange="onchangeShow(this.value)"></s:select></td><tdwidth="10%"height="25"class="alignLeft">工单类型:</td><tdwidth="10%"valign="top"class="alignLeft"><selectname="form.gongdanType"id="type"></select></td>
上面写了两个请求的函数,代码一样,只不过在第一级下拉列表onchange时,第二级下拉列表要定位在第一个值“全部”。
action
Java代码
publicclassGongdanTypeStatActionextendsActionSupportimplementsPreparable{
privateStringtype;
privateList<Param>categorys;
privateList<Param>gongdanTypes;
privateStringstatCategory;
publicvoidprepare()throwsException{
type=ServletActionContext.getRequest().getParameter("type");
categorys=newArrayList<Param>();
Paramparam1=newParam();
param1.setValue("CB");
param1.setValueName("业务变更");
Paramparam2=newParam();
param2.setValue("APP");
param2.setValueName("资源申请");
categorys.add(param1);
categorys.add(param2);
}
//得到业务变更和资源申请下的变更类别
publicvoidajaxGetType()throwsException{
//工单类型
if("CB".equals(statCategory)){
gongdanTypes=newArrayList<Param>();
for(EChangeBusinessCategoryec:EChangeBusinessCategory.values()){
Paramparam=newParam();
param.setValue(ec.getKey());
param.setValueName(ec.getLable());
gongdanTypes.add(param);
}
}elseif("APP".equals(statCategory)){
gongdanTypes=newArrayList<Param>();
for(EApplyTypeet:EApplyType.values()){
Paramparam=newParam();
param.setValue(et.getKey());
param.setValueName(et.getName());
gongdanTypes.add(param);
}
}
JSONArrayjsonObj=JSONArray.fromObject(gongdanTypes);
sendMsg(jsonObj.toString());//发送JSON格式的字符串回JS端
}
publicvoidsendMsg(Stringcontent)throwsIOException{
HttpServletResponseresponse=ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.getWriter().write(content);
}
}
publicclassGongdanTypeStatActionextendsActionSupportimplementsPreparable{privateStringtype;privateList<Param>categorys;privateList<Param>gongdanTypes;privateStringstatCategory;publicvoidprepare()throwsException{type=ServletActionContext.getRequest().getParameter("type");categorys=newArrayList<Param>();Paramparam1=newParam();param1.setValue("CB");param1.setValueName("业务变更");Paramparam2=newParam();param2.setValue("APP");param2.setValueName("资源申请");categorys.add(param1);categorys.add(param2);}//得到业务变更和资源申请下的变更类别publicvoidajaxGetType()throwsException{//工单类型if("CB".equals(statCategory)){gongdanTypes=newArrayList<Param>();for(EChangeBusinessCategoryec:EChangeBusinessCategory.values()){Paramparam=newParam();param.setValue(ec.getKey());param.setValueName(ec.getLable());gongdanTypes.add(param);}}elseif("APP".equals(statCategory)){gongdanTypes=newArrayList<Param>();for(EApplyTypeet:EApplyType.values()){Paramparam=newParam();param.setValue(et.getKey());param.setValueName(et.getName());gongdanTypes.add(param);}}JSONArrayjsonObj=JSONArray.fromObject(gongdanTypes);sendMsg(jsonObj.toString());//发送JSON格式的字符串回JS端}publicvoidsendMsg(Stringcontent)throwsIOException{HttpServletResponseresponse=ServletActionContext.getResponse();response.setCharacterEncoding("UTF-8");response.getWriter().write(content);}}
Param.java
Java代码
publicclassParam{
privateObjectentity;
privateStringvalue;
privateStringvalueName;
publicParam(){
}
publicParam(Stringvalue,StringvalueName){
this.value=value;
this.valueName=valueName;
}
publicStringgetValue(){
returnvalue;
}
publicvoidsetValue(Stringvalue){
this.value=value;
}
publicStringgetValueName(){
returnvalueName;
}
publicvoidsetValueName(StringvalueName){
this.valueName=valueName;
}
publicObjectgetEntity(){
returnentity;
}
publicvoidsetEntity(Objectentity){
this.entity=entity;
}
}
publicclassParam{privateObjectentity;privateStringvalue;privateStringvalueName;publicParam(){}publicParam(Stringvalue,StringvalueName){this.value=value;this.valueName=valueName;}publicStringgetValue(){returnvalue;}publicvoidsetValue(Stringvalue){this.value=value;}publicStringgetValueName(){returnvalueName;}publicvoidsetValueName(StringvalueName){this.valueName=valueName;}publicObjectgetEntity(){returnentity;}publicvoidsetEntity(Objectentity){this.entity=entity;}}
两个枚举类型
EChangeBusinessCategory.java
EApplyType.java
Java代码
publicenumEChangeBusinessCategory{
//系统安装
SYSTEM_SETUP("SYS","系统安装"),
//监控需求
MONITOR_DEMAND("MONI","监控需求"),
//机柜需求
CABINETS_DEMAND("CABI","机柜需求"),
//撤销存储
STORAGE_DEMAND("STOR","撤销存储"),
//网络需求
NETWORK_DEMAND("NET","网络需求");
privateStringkey;
privateStringlable;
EChangeBusinessCategory(Stringkey,Stringvalue){
this.key=key;
this.lable=value;
}
publicstaticEChangeBusinessCategorygetEnumType(Stringkey){
EChangeBusinessCategory[]values=EChangeBusinessCategory.values();
for(inti=0;i<values.length;i++){
EChangeBusinessCategoryeInfo=values[i];
if(eInfo.getKey().equals(key)){
returneInfo;
}
}
returnnull;
}
publicStringgetLable(){
returnlable;
}
publicStringgetKey(){
returnkey;
}
}
publicenumEApplyType{
SERV("SERV","服务器"),
CABI("CABI","机柜"),
IP("IP","IP"),
STOR("STOR","存储");
privateStringkey;
privateStringname;
EApplyType(Stringkey,Stringname){
this.key=key;
this.name=name;
}
publicStringgetKey(){
returnkey;
}
publicStringgetName(){
returnname;
}
publicstaticEApplyTypegetEnumType(Stringkey){
EApplyType[]values=EApplyType.values();
for(inti=0;i<values.length;i++){
EApplyTypeeInfo=values[i];
if(eInfo.getKey().equals(key)){
returneInfo;
}
}
returnnull;
}
}
publicenumEChangeBusinessCategory{//系统安装SYSTEM_SETUP("SYS","系统安装"),//监控需求MONITOR_DEMAND("MONI","监控需求"),//机柜需求CABINETS_DEMAND("CABI","机柜需求"),//撤销存储STORAGE_DEMAND("STOR","撤销存储"),//网络需求NETWORK_DEMAND("NET","网络需求");privateStringkey;privateStringlable;EChangeBusinessCategory(Stringkey,Stringvalue){this.key=key;this.lable=value;}publicstaticEChangeBusinessCategorygetEnumType(Stringkey){EChangeBusinessCategory[]values=EChangeBusinessCategory.values();for(inti=0;i<values.length;i++){EChangeBusinessCategoryeInfo=values[i];if(eInfo.getKey().equals(key)){returneInfo;}}returnnull;}publicStringgetLable(){returnlable;}publicStringgetKey(){returnkey;}}publicenumEApplyType{SERV("SERV","服务器"),CABI("CABI","机柜"),IP("IP","IP"),STOR("STOR","存储");privateStringkey;privateStringname;EApplyType(Stringkey,Stringname){this.key=key;this.name=name;}publicStringgetKey(){returnkey;}publicStringgetName(){returnname;}publicstaticEApplyTypegetEnumType(Stringkey){EApplyType[]values=EApplyType.values();for(inti=0;i<values.length;i++){EApplyTypeeInfo=values[i];if(eInfo.getKey().equals(key)){returneInfo;}}returnnull;}}
action配置
Java代码
<actionname="ajaxGetType"class="GongdanTypeStatAction"
method="ajaxGetType">
</action>
<actionname="ajaxGetType"class="GongdanTypeStatAction"method="ajaxGetType"></action>