`
flash59
  • 浏览: 96179 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

基础:用js结合struts实现不刷新页面查询数据

阅读更多

我遇到一个需求,可能大伙也遇见过这样的需求,那就是在页面上提供省和市的列表供用户选择输入,当选择某个省时,市的列表立即改变成这个省里的城市,很简单吧,刚开始时想调用list的onChange方法直接到后面取数据,然后刷新整个页面,改变城市列表的内容,考虑到网络后台处理时要执行很多无关的逻辑处理,所以想到只刷新城市列表那一个控件,那就请出名躁一时的ajax吧!

实现这个功能并不复杂,结合struts一会工夫就搞定了:下面是我的做法

首先描述一下AJAX在Struts框架中的位置和作用:

      STRUTS框架实现了MVC模式,大家都知道这个模式,也知道STRUTS数据流的过程,简单讲,VIEW.jsp发送请求到CONTROL :action.do,action.do来选择业务处理模块,在业务处理模块中更新MODEL:model.java ,并请求action.do选择VIEW.jsp,发送回客户VIEW,而AJAX在VIEW端发送xmlhttprequest给action.do,然后像普通处理一样更新MODEL,不同的是,要由MODEL来生成带有返回数据的XML给客户端VIEW,可以看到,这个过程省略了选择VIEW.jsp的过程,所以,客户端没有刷新页面,但数据已经传到VIEW了。

      我的应用中稍微改变了一下做法,处理完请求后,再交给ACTION来选择VIEW.jsp,不过这个jsp文件和页面的相同,这样在客户端就收到一个和现有页面只有一小部分不同的HTML代码,那部分不同的代码就是要在页面上更新的数据,只要在得到数据后将那部分数据分离出来显示在页面上,就可以实现无刷新页面的更新效果了。。。

      jsp代码:

  1. <script type="text/javascript">
  2.  function getCity()
       {
           //alert("begin1");
           retrieveURL('/xxxx/netinfo.do?method=getCity','NetinfoForm');//document.forms[0].submit();
       }
  3. </script>
  4. <script type="text/javascript" src="/xxxx/scripts/Ajax.js"></script>
  5. <tr bgcolor="#F7FDFD">      
  6.     <td  class="right">省份:  td>      
  7.     <td>      
  8.         <html:select property="province" size="1" onchange="javascript:getCity();" >      
  9.             <logic:iterate id="prov" name="NetinfoForm" property="province_list">      
  10.                 <%String nid= ((Province)prov).getId().toString();%>      
  11.                 <html:option value="<!---->"><bean:write name="prov" property="name"/>html:option>      
  12.              logic:iterate>      
  13.         html:select>      
  14.     td>      
  15.     <td  class="right">城市:  td>      
  16.     <td>      
  17.         <span name="change" id="change">        
  18.             <html:select property="city" size="1" >      
  19.                 <logic:iterate id="cit" name="NetinfoForm" property="city_list">      
  20.     <%String nid= ((City)cit).getId().toString();%>      
  21.     <html:option value="<!---->"><bean:write name="cit" property="name"/>html:option>      
  22.                logic:iterate>      
  23.            html:select>      
  24.     td>             
  25. tr>    

action.do代码

  1. public ActionForward getCity(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {   
  2.     int provinceId=Integer.parseInt(request.getParameter("province"));   
  3.     ArrayList<city></city> city_list=(ArrayList<city></city>)cityManager.getCityByProvince(provinceId);   
  4.     object.setCity_list(city_list);   
  5.     initForm(form, request, object);   
  6.     mapping.findForward(SUCCESS);   
  7.  //转向原页面,请保证jsp页面上的其他无关元素都能得到初始化,否则,struts 在生成html代码的时候会报错,而在客户端却没有任何反应,所以在这个方法中把所有元素都准备好。  

关键部分:ajax.js代码:

js 代码
  1. //global variables   
  2.   var req;   
  3.   var which;   
  4.   
  5.   
  6.   /**  
  7.    * Get the contents of the URL via an Ajax call  
  8.    * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1)   
  9.    * nodeToOverWrite - when callback is made  
  10.    * nameOfFormToPost - which form values will be posted up to the server as part   
  11.    *                    of the request (can be null)  
  12.    */  
  13.   function retrieveURL(url,nameOfFormToPost) {   
  14.     document.getElementById("change").innerHTML = "loading...";   
  15.     //alert("retrieveURL");   
  16.     //get the (form based) params to push up as part of the get request   
  17.     poststr=getFormAsString(nameOfFormToPost);   
  18.     //poststr=encodeURIComponent(poststr);   
  19.     //poststr=encodeURI(poststr);   
  20.     //alert("url="+url+poststr);   
  21.     //Do the Ajax call   
  22.     if (window.XMLHttpRequest) { // Non-IE browsers   
  23.       req = new XMLHttpRequest();   
  24.       //req.setRequestHeader( "Content-Type", "text/html;charset=UTF-8" );   
  25.       req.setRequestHeader("Content-type""application/x-www-form-urlencoded");   
  26.          
  27.       req.onreadystatechange = processStateChange;   
  28.       try {   
  29.         req.open("POST", url, true); //was get   
  30.       } catch (e) {   
  31.         //alert("Problem Communicating with Server\n"+e);   
  32.       }   
  33.       req.send(null);   
  34.     } else if (window.ActiveXObject) { // IE   
  35.       //alert("IE");   
  36.       req = new ActiveXObject("Microsoft.XMLHTTP");   
  37.       if (req) {   
  38.         req.onreadystatechange = processStateChange;   
  39.         req.open("POST", url+poststr, true);   
  40.         req.send();   
  41.       }   
  42.     }   
  43.   }   
  44.     
  45.  /**  
  46.   * gets the contents of the form as a URL encoded String  
  47.   * suitable for appending to a url  
  48.   * @param formName to encode  
  49.   * @return string with encoded form values , beings with &  
  50.   */    
  51.  function getFormAsString(formName){   
  52.     //alert("getFormAsString");   
  53.     //Setup the return String   
  54.     returnString ="";   
  55.        
  56.     //Get the form values   
  57.     formElements=document.forms[formName].elements;   
  58.   
  59.     //loop through the array , building up the url   
  60.     //in the form /strutsaction.do&name=value   
  61.        
  62.     for ( var i=formElements.length-1; i>=0; --i ){   
  63.         //we escape (encode) each value   
  64.         ////只取省的名字   
  65.         //if(formElements[i].name=="province")   
  66.         //{   
  67.             //alert("formElements[i].value="+formElements[i].value);   
  68.             returnString=returnString+"&"+formElements[i].name+"="+formElements[i].value;   
  69.         //}   
  70.         //if(formElements[i].name=="sourcepage")   
  71.         //{   
  72.            // alert("formElements[i].value="+formElements[i].value);   
  73.             //returnString=returnString+"&"+formElements[i].name+"="+formElements[i].value;   
  74.         //}   
  75.         //returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);   
  76.     }   
  77.     //alert("returnString="+returnString);   
  78.     //return the values   
  79.     return returnString;    
  80.  }   
  81.     
  82.  /*  
  83.    * Set as the callback method for when XmlHttpRequest State Changes   
  84.    * used by retrieveUrl  
  85.   */  
  86.   function processStateChange() {   
  87.       //alert("processStateChange");   
  88.       if (req.readyState == 4) { // Complete   
  89.       if (req.status == 200) { // OK response   
  90.            
  91.         //alert("Ajax response:"+req.responseText);   
  92.            
  93.         //Split the text response into Span elements   
  94.         spanElements = splitTextIntoSpan(req.responseText);   
  95.            
  96.         //Use these span elements to update the page   
  97.         replaceExistingWithNewHtml(spanElements);   
  98.            
  99.       } else {   
  100.         //alert("Problem with server response:\n " + req.statusText);   
  101.       }   
  102.     }   
  103.   }   
  104.     
  105.  /**  
  106.  * Splits the text into  elements  
  107.  * @param the text to be parsed  
  108.  * @return array of  elements - this array can contain nulls   )   
  109.  */  
  110.  function splitTextIntoSpan(textToSplit){   
  111.        
  112.     //Split the document   
  113.     returnElements=textToSplit.split(""
  114.     //Process each of the elements     
  115.     for ( var i=returnElements.length-1; i>=0; --i ){   
  116.            
  117.         //Remove everything before the 1st span   
  118.         spanPos = returnElements[i].indexOf(");          
  119.            
  120.         //if we find a match , take out everything before the span   
  121.         if(spanPos>0){   
  122.             subString=returnElements[i].substring(spanPos);   
  123.             returnElements[i]=subString;   
  124.            
  125.         }    
  126.     }   
  127.     //alert(returnElements[0]);   
  128.     return returnElements;   
  129.  }   
  130.     
  131.  /*  
  132.   * Replace html elements in the existing (ie viewable document)  
  133.   * with new elements (from the ajax requested document)  
  134.   * WHERE they have the same name AND are  elements  
  135.   * @param newTextElements (output of splitTextIntoSpan)  
  136.   *                 in the format texttoupdate  
  137.   */  
  138.  function replaceExistingWithNewHtml(newTextElements){   
  139.      //alert("newTextElements="+newTextElements);   
  140.     //loop through newTextElements   
  141.     for ( var i=newTextElements.length-1; i>=0; --i ){   
  142.      
  143.         //check that this begins with   
  144.         if(newTextElements[i].indexOf(")>-1){   
  145.                
  146.             //get the name - between the 1st and 2nd quote mark   
  147.             startNamePos=newTextElements[i].indexOf('"')+1;  
  148.             endNamePos=newTextElements[i].indexOf('"',startNamePos);   
  149.             name=newTextElements[i].substring(startNamePos,endNamePos);   
  150.                
  151.             if(name=="change")   
  152.             {   
  153.                 //alert("#"+name+"#");   
  154.                 //get the content - everything after the first > mark   
  155.                 startContentPos=newTextElements[i].indexOf('>')+1;   
  156.                 content=newTextElements[i].substring(startContentPos);   
  157.                    
  158.                 //alert(content);   
  159.                 //Now update the existing Document with this element   
  160.                 //check that this element exists in the document   
  161.                 //document.all.link1.href   
  162.                 if(document.getElementById(name)){   
  163.                 //if(document.all.name){   
  164.                     //alert("Replacing Element:"+name);   
  165.                     document.getElementById(name).innerHTML = content;   
  166.                 } else {   
  167.                     document.getElementById("change").innerHTML = "error,retry!";   
  168.                     //alert("Element:"+name+"not found in existing document");   
  169.                 }   
  170.             }   
  171.         }   
  172.     }   
  173.  }   
分享到:
评论
3 楼 flash59 2007-08-20  
毕竟这个项目不是以AJAX为主的东东啊,整个项目只有这个功能使用了,不过,有机会一定好好学习一下相关的框架,请问有比较流行和实用的框架推荐一下吗?
2 楼 mark.li.guyu 2007-08-17  
目前AJAX技术虽然不能说成熟,但是已经有很多框架可以借鉴了,无论是RIA类型的还是RPC类型的
1 楼 泡泡 2007-08-17  
楼主还生活在2001年?

相关推荐

Global site tag (gtag.js) - Google Analytics