首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

jquery异步请务实例

2013-03-14 
jquery异步请求实例1、用ajaxjsp代码如下:$.ajax({type:get,dataType:json,url:%basePath%actionSm

jquery异步请求实例
1、用ajax

jsp代码如下:


$.ajax({                type:"get",                dataType:"json",                url:"<%=basePath%>actionSmUser.do?method=getUserMsgByUserId",                data:"userId="+userId,                success:function(msg){                    var data = 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返回字符串的组织形式可采用JSONArray array 的方式,返回array.toJSONString();



















本文是要做一个二级联动,动态的。通过jquery返回json类型的数据,然后在jsp页面处理,生成第二级下拉列表菜单。
所需js库: jquery.js,json2.js
jar包:json-lib-2.2.3-jdk15.jar,ezmorph-1.0.6.jar


Java代码
<%@ page contentType="text/html; charset=UTF-8"%>  
<%@ taglib prefix="s" uri="/struts-tags"%>  
<script type="text/javascript" src="jquery.js"></script>  
<script type="text/javascript" src="json2.js"></script>  
  
<script type="text/javascript">  
jQuery(function($){  
var obj=$("#category");  
if(typeof obj != 'undefined' && obj !=''){  
    showGongdanType(obj.val());  
}  
});  
function onchangeShow(category){  
jQuery.ajax({  
url : "${contextPath}/assets/statistic/ajaxGetType.do",  
data : {statCategory : category},  // 传递参数  
type : "post",  
cache : false,  
dataType : "json",  
success:onchangecallback  
});  
}  
function onchangecallback(data){   
    document.all['type'].options.length = 0;  
    var str="<option value=''>全部</option>";  
    for(var i=0;i<data.length;i++){  
        str+="<option value='"+data[i].value+"'>"+data[i].valueName+"</option>"  
    }  
    $("#type").html(str);  
}  
function showGongdanType(category){  
jQuery.ajax({  
url : "${contextPath}/assets/statistic/ajaxGetType.do",  
data : {statCategory : category},  
type : "post",  
cache : false,  
dataType : "json",  
success:callback  
});  
}  
function callback(data){   
      document.all['type'].options.length = 0;  
    var str="<option value=''>全部</option>";  
    for(var i=0;i<data.length;i++){  
     str+="<option value='"+data[i].value+"'>"+data[i].valueName+"</option>"  
    }  
    $("#type").html(str);  
// 下面代码是为了第二级下拉列表的定位。因为非struts2的标签,无法自己定位  
    if("${gongdanType}"!=''){  
        for(var i=0;i<data.length;i++){  
            if(data[i].value=="${gongdanType}")  
            document.all['type'].selectedIndex=i+1;  
        }  
    }  
}  
</script>  
  
            <td width="10%" height="25" valign="top" list="categorys" id="category"  
                        listKey="value" listValue="valueName"   
                        onchange="onchangeShow(this.value)">  
                    </s:select>  
            </td>  
            <td width="10%" height="25" valign="top" id="type" >  
            </select></td>  
<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="json2.js"></script><script type="text/javascript">jQuery(function($){ var obj=$("#category"); if(typeof obj != 'undefined' && obj !=''){ showGongdanType(obj.val());}}); function onchangeShow(category){jQuery.ajax({ url : "${contextPath}/assets/statistic/ajaxGetType.do", data : {statCategory : category}, // 传递参数 type : "post", cache : false, dataType : "json", success:onchangecallback});} function onchangecallback(data){ document.all['type'].options.length = 0; var str="<option value=''>全部</option>"; for(var i=0;i<data.length;i++){ str+="<option value='"+data[i].value+"'>"+data[i].valueName+"</option>"} $("#type").html(str);} function showGongdanType(category){jQuery.ajax({ url : "${contextPath}/assets/statistic/ajaxGetType.do", data : {statCategory : category}, type : "post", cache : false, dataType : "json", success:callback});} function callback(data){ document.all['type'].options.length = 0; var str="<option value=''>全部</option>"; for(var i=0;i<data.length;i++){ str+="<option value='"+data[i].value+"'>"+data[i].valueName+"</option>"} $("#type").html(str); // 下面代码是为了第二级下拉列表的定位。因为非struts2的标签,无法自己定位 if("${gongdanType}"!=''){ for(var i=0;i<data.length;i++){ if(data[i].value=="${gongdanType}") document.all['type'].selectedIndex=i+1;}}}</script><td width="10%" height="25" valign="top" list="categorys" id="category" listKey="value" listValue="valueName" onchange="onchangeShow(this.value)"></s:select></td><td width="10%" height="25" valign="top" id="type" ></select></td>


上面写了两个请求的函数,代码一样,只不过在第一级下拉列表onchange时,第二级下拉列表要定位在第一个值“全部”。


action

Java代码
public class GongdanTypeStatAction extends ActionSupport implements Preparable {  
      
    private String type;  
      
    private List<Param> categorys;  
      
    private List<Param> gongdanTypes;  
      
    private String statCategory;  
  
    public void prepare() throws Exception {  
        type = ServletActionContext.getRequest().getParameter("type");  
        categorys = new ArrayList<Param>();  
        Param param1 = new Param();  
        param1.setValue("CB");  
        param1.setValueName("业务变更");  
        Param param2 = new Param();  
        param2.setValue("APP");  
        param2.setValueName("资源申请");  
        categorys.add(param1);  
        categorys.add(param2);  
    }  
      
    // 得到业务变更和资源申请下的变更类别  
    public void ajaxGetType() throws Exception {  
        // 工单类型  
        if("CB".equals(statCategory)){  
            gongdanTypes = new ArrayList<Param>();  
            for(EChangeBusinessCategory ec:EChangeBusinessCategory.values()){  
                Param param = new Param();  
                param.setValue(ec.getKey());  
                param.setValueName(ec.getLable());  
                gongdanTypes.add(param);  
            }  
        }else if("APP".equals(statCategory)){  
            gongdanTypes = new ArrayList<Param>();  
            for (EApplyType et : EApplyType.values()) {  
                Param param = new Param();  
                param.setValue(et.getKey());  
                param.setValueName(et.getName());  
                gongdanTypes.add(param);  
            }  
        }  
        JSONArray jsonObj = JSONArray.fromObject(gongdanTypes);  
        sendMsg(jsonObj.toString());    //发送JSON格式的字符串回JS端      
    }  
      
    public void sendMsg(String content) throws IOException{      
        HttpServletResponse response = ServletActionContext.getResponse();      
        response.setCharacterEncoding("UTF-8");      
        response.getWriter().write(content);      
    }    
}  
public class GongdanTypeStatAction extends ActionSupport implements Preparable { private String type; private List<Param> categorys; private List<Param> gongdanTypes; private String statCategory; public void prepare() throws Exception { type = ServletActionContext.getRequest().getParameter("type"); categorys = new ArrayList<Param>(); Param param1 = new Param(); param1.setValue("CB"); param1.setValueName("业务变更"); Param param2 = new Param(); param2.setValue("APP"); param2.setValueName("资源申请"); categorys.add(param1); categorys.add(param2);} // 得到业务变更和资源申请下的变更类别 public void ajaxGetType() throws Exception { // 工单类型 if("CB".equals(statCategory)){ gongdanTypes = new ArrayList<Param>(); for(EChangeBusinessCategory ec:EChangeBusinessCategory.values()){ Param param = new Param(); param.setValue(ec.getKey()); param.setValueName(ec.getLable()); gongdanTypes.add(param);}}else if("APP".equals(statCategory)){ gongdanTypes = new ArrayList<Param>(); for (EApplyType et : EApplyType.values()) { Param param = new Param(); param.setValue(et.getKey()); param.setValueName(et.getName()); gongdanTypes.add(param);}} JSONArray jsonObj = JSONArray.fromObject(gongdanTypes); sendMsg(jsonObj.toString()); //发送JSON格式的字符串回JS端 } public void sendMsg(String content) throws IOException{ HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.getWriter().write(content); } }



Param.java

Java代码
  
public class Param {  
  
    private Object entity;  
  
      
    private String value;  
  
      
    private String valueName;  
  
    public Param() {  
  
    }  
  
      
    public Param(String value, String valueName) {  
        this.value = value;  
        this.valueName = valueName;  
    }  
  
      
    public String getValue() {  
        return value;  
    }  
  
      
    public void setValue(String value) {  
        this.value = value;  
    }  
  
      
    public String getValueName() {  
        return valueName;  
    }  
  
      
    public void setValueName(String valueName) {  
        this.valueName = valueName;  
    }  
  
      
    public Object getEntity() {  
        return entity;  
    }  
  
      
    public void setEntity(Object entity) {  
        this.entity = entity;  
    }  
  
}  
public class Param { private Object entity; private String value; private String valueName; public Param() {} public Param(String value, String valueName) { this.value = value; this.valueName = valueName;} public String getValue() { return value;} public void setValue(String value) { this.value = value;} public String getValueName() { return valueName;} public void setValueName(String valueName) { this.valueName = valueName;} public Object getEntity() { return entity;} public void setEntity(Object entity) { this.entity = entity;}}


两个枚举类型
EChangeBusinessCategory.java
EApplyType.java

Java代码
public enum EChangeBusinessCategory {  
  
    // 系统安装  
    SYSTEM_SETUP("SYS", "系统安装"),  
    // 监控需求  
    MONITOR_DEMAND("MONI", "监控需求"),  
    // 机柜需求  
    CABINETS_DEMAND("CABI", "机柜需求"),  
      
    // 撤销存储  
    STORAGE_DEMAND("STOR","撤销存储"),  
    // 网络需求  
    NETWORK_DEMAND("NET", "网络需求");  
  
    private String key;  
  
    private String lable;  
  
  
    EChangeBusinessCategory(String key, String value) {  
        this.key = key;  
        this.lable = value;  
    }  
  
      
    public static EChangeBusinessCategory getEnumType(String key) {  
        EChangeBusinessCategory[] values = EChangeBusinessCategory.values();  
        for (int i = 0; i < values.length; i++) {  
            EChangeBusinessCategory eInfo = values[i];  
            if (eInfo.getKey().equals(key)) {  
                return eInfo;  
            }  
        }  
        return null;  
    }  
  
      
    public String getLable() {  
        return lable;  
    }  
  
      
    public String getKey() {  
        return key;  
    }  
  
}  
  
  
public enum EApplyType {  
  
    SERV("SERV", "服务器"),  
  
    CABI("CABI", "机柜"),  
  
    IP("IP", "IP"),  
  
    STOR("STOR", "存储");  
  
    private String key;  
  
    private String name;  
  
      
    EApplyType(String key, String name) {  
        this.key = key;  
        this.name = name;  
    }  
  
      
    public String getKey() {  
        return key;  
    }  
  
      
    public String getName() {  
        return name;  
    }  
  
      
    public static EApplyType getEnumType(String key) {  
        EApplyType[] values = EApplyType.values();  
        for (int i = 0; i < values.length; i++) {  
            EApplyType eInfo = values[i];  
            if (eInfo.getKey().equals(key)) {  
                return eInfo;  
            }  
        }  
        return null;  
    }  
}  
public enum EChangeBusinessCategory { // 系统安装 SYSTEM_SETUP("SYS", "系统安装"), // 监控需求 MONITOR_DEMAND("MONI", "监控需求"), // 机柜需求 CABINETS_DEMAND("CABI", "机柜需求"), // 撤销存储 STORAGE_DEMAND("STOR","撤销存储"), // 网络需求 NETWORK_DEMAND("NET", "网络需求"); private String key; private String lable; EChangeBusinessCategory(String key, String value) { this.key = key; this.lable = value;} public static EChangeBusinessCategory getEnumType(String key) { EChangeBusinessCategory[] values = EChangeBusinessCategory.values(); for (int i = 0; i < values.length; i++) { EChangeBusinessCategory eInfo = values[i]; if (eInfo.getKey().equals(key)) { return eInfo;}} return null;} public String getLable() { return lable;} public String getKey() { return key;}} public enum EApplyType { SERV("SERV", "服务器"), CABI("CABI", "机柜"), IP("IP", "IP"), STOR("STOR", "存储"); private String key; private String name; EApplyType(String key, String name) { this.key = key; this.name = name;} public String getKey() { return key;} public String getName() { return name;} public static EApplyType getEnumType(String key) { EApplyType[] values = EApplyType.values(); for (int i = 0; i < values.length; i++) { EApplyType eInfo = values[i]; if (eInfo.getKey().equals(key)) { return eInfo;}} return null;}}



action配置

Java代码
<action name="ajaxGetType" method="ajaxGetType"></action>


热点排行