Home > Web Front-end > JS Tutorial > body text

Detailed explanation of ajax application examples of DOM objects

零下一度
Release: 2017-07-02 09:35:43
Original
1345 people have browsed it

Requirements: Click the drop-down option box, select a data type, and automatically display the names of all data items under this type in the form, that is, all unique ddlNames corresponding to the same keyword in the database.

1. Add:

<script type="text/javascript" src="${pageContext.request.contextPath }/script/pub.js?1.1.11"></script>
Copy after login
# to dictionaryIndex.jsp
##2. Code for calling js:

function changetype(){        
          if(document.Form1.keyword.value=="jerrynew"){            
             
               var textStr="<input type=\"text\" name=\"keywordname\" maxlength=\"50\" size=\"24\"> ";
             document.getElementById("newtypename").innerHTML="类型名称:";
             document.getElementById("newddlText").innerHTML=textStr;
             
             
             Pub.submitActionWithForm('Form2','${pageContext.request.contextPath }/system/elecSystemDDLAction_edit.do','Form1');
            
          }else{            var textStr="";
            document.getElementById("newtypename").innerHTML="";
            document.getElementById("newddlText").innerHTML=textStr;             /**
                * 参数一:传递dictionaryIndex.jsp的From2的表单
                * 参数二:传递URL路径地址
                * 参数三:传递dictionaryIndex.jsp的From1的表单
                
                原理:使用Ajax
                * 传递dictionaryIndex.jsp中表单Form1中的所有元素作为参数,传递给服务器,并在服务器进行处理
                * 将处理后的结果放置到dictionaryEdit.jsp中
                * 将dictionaryEdit.jsp页面的全部内容放置到dictionaryIndex.jsp表单Form2中*/Pub.submitActionWithForm('Form2','${pageContext.request.contextPath }/system/elecSystemDDLAction_edit.do','Form1');
          }  
       }
Copy after login
View Code

Where submitActionWithForm Methods are defined in pub.js.

3. Define 5 methods in pub.js:

 (1) Pub.submitActionWithForm method

/***
 * domId:表单Form2的名称
 * action:表示URL连接
 * sForm:表单Form1的名称 */Pub.submitActionWithForm=function(domId,action,sForm){  /**第一步:创建Ajax引擎对象*/
  var req = Pub.newXMLHttpRequest();  /**第二步:req.onreadystatechange表示事件处理函数(相当于一个监听),用来监听客户端与服务器端的连接状态*/
  var handlerFunction = Pub.getReadyStateHandler(req, domId,Pub.handleResponse);
  req.onreadystatechange = handlerFunction;  /**第三步:打开一个连接,要求:如果是POST请求,需要设置一个头部信息,否则此时不能使用req.send()方法向服务器发送数据*/
  req.open("POST", action, true);
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
  /**第四步:向服务器发送数据,格式:name=张三&age=28*/
  var str = Pub.getParams2Str(sForm); 
  //传递表单Form1中的元素作为参数给服务器  req.send(str);
}
Copy after login
 (2) Pub.newXMLHttpRequest method

/**
 * 用于创建ajax引擎 */Pub.newXMLHttpRequest=function newXMLHttpRequest() {  var xmlreq = false;  if (window.XMLHttpRequest) {xmlreq = new XMLHttpRequest();
  } else if (window.ActiveXObject) {     try {
      
      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {       
      try {
      
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
          
        alert(e2);
      }
    }
  }  return xmlreq;
}
Copy after login
 

xmlreq = new XMLHttpRequest() is the core object of Ajax operation

 (3)Pub.getParams2Str method

/**
 * @Description:传递表单Form1中的元素作为参数
 * @param sForm:传递表单Form1的名称
 * @returns {String}:使用ajax返回服务器端的参数,传递的就是表单Form1中元素的参数 */Pub.getParams2Str=function getParams2Str(sForm){ var strDiv="";      
 try {var objForm=document.forms[sForm];  if (!objForm)return strDiv;  var elt,sName,sValue;  for (var fld = 0; fld < objForm.elements.length; fld++) {
      elt = objForm.elements[fld];    
      sName=elt.name;
      sValue=""+elt.value;      if(fld==objForm.elements.length-1)
          strDiv=strDiv + sName+"="+sValue+"";       else   
          strDiv=strDiv + sName+"="+sValue+"&";
   }


  }  catch (ex) {return strDiv;
    } 
   return strDiv;
}
Copy after login
 (4)Pub.getReadyStateHandler method

=  (req.readyState == 4   (req.status == 200"HTTP error: "+
Copy after login
 (5)Pub .handleResponse method

/**
 * @Description:将结果返回dictionaryEdit.jsp,并放置到dictionaryIndex.jsp的Form2中
 * @param data:服务器返回的结果
 * @param eleid:表单Form2的名称 */Pub.handleResponse= function handleResponse(data,eleid){      //获取表单Form2的对象  var ele =document.getElementById(eleid);      //将返回的结果放置到表单Form2的元素中  ele.innerHTML = data;
    
}
Copy after login
 

The next step is to operate the Action class. You need to query the corresponding ddlName in the database based on the keyword. Operation:

 

4. Add the Edit() method in ElecSystemDDLAction

/**  
    * @Name: edit
    * @Description: 跳转到数据字典编辑页面
    * @Parameters: 无
    * @Return: String:跳转到system/dictionaryEdit.jsp*/public String edit(){//1.获取数据类型String keyword = elecSystemDDL.getKeyword();//2.使用数据类型查询数据字典,返回List<ElecSystemDDL>List<ElecSystemDDL> list=elecSystemDDLService.findSystemDDLListByKeyword(keyword);
        request.setAttribute("list", list);return "edit";
    }
Copy after login
5.Declare in IElecSystemDDLService

List<ElecSystemDDL> findSystemDDLListByKeyword(String keyword);
Copy after login
6. Overriding method in ElecSystemDDLServiceImpl

/**  
    * @Name: findSystemDDLListByKeyword
    * @Description: 根据数据类型名称查询数据字典
    * @Parameters: keyword:数据类型名称
    * @Return: List:存储ElecSystemDDL对象集合*/@Overridepublic List<ElecSystemDDL> findSystemDDLListByKeyword(String keyword) {//查询条件String condition="";//查询条件对应的参数List<Object> paramsList = new ArrayList<Object>();if(StringUtils.isNotBlank(keyword)){
            condition=" and o.keyword=?";
            paramsList.add(keyword);
        }//传递可变参数Object[] params = paramsList.toArray();//排序Map<String, String> orderby = new  LinkedHashMap<String, String>();
        orderby.put("o.ddlCode", "asc");
        List<ElecSystemDDL> list = elecSystemDDLDao.findCollectionByConditionNoPage(condition, params, orderby);return list;
    }
Copy after login
 

The findCollectionByConditionNoPage(condition, params, orderby) method is implemented by commonDao according to the specified Condition, method to return query result set (without paging)

7.dictionaryEdit.jsp traverses the value of the object

<%@taglib uri="/struts-tags" prefix="s"%>
Copy after login
<s:if test="#request.list!=null && #request.list.size()>0">
                    <s:iterator value="#request.list">
                        <tr>
                           <td class="ta_01" align="center"  width="20%"><s:property value="ddlCode"/></td>
                           <td class="ta_01" align="center"  width="60%">
                                   <input id="<s:property value="ddlCode"/>" name="itemname" type="text" value="<s:property value="ddlName"/>"  size="45" maxlength="25"></td>
                           <td class="ta_01" align="center"  width="20%">
                                   <a href="#" onclick="delTableRow('<s:property value="ddlCode"/>')">
                            <img src="${pageContext.request.contextPath }/images/delete.gif" width="16" height="16" border="0" style="CURSOR:hand"></a>
                          </td>
                        </tr>
                    </s:iterator>
                </s:if>
                <s:else>
                    <tr>
                       <td class="ta_01" align="center"  width="20%">1</td>
                       <td class="ta_01" align="center"  width="60%">
                               <input name="itemname" type="text"  size="45" maxlength="25">
                       </td>
                       <td class="ta_01" align="center"  width="20%"></td>
                    </tr>
                </s:else>
Copy after login

Effect display:

 

Complete the selection type list and realize the content replacement of the Form2 form.

The above is the detailed content of Detailed explanation of ajax application examples of DOM objects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template