选择显示字体大小

ajax实例入门

  一、开门见山

  这些时间,瞎子也看得见,ajax正大踏步的朝我们走来。不管我们是拥护也好,反对也罢,还是视而不见,ajax像一阵潮流,席转了我们所有的人。

  关于ajax的定义也好,大话也好,早有人在网上发表了汗牛充栋的文字,在这里我也不想照本宣科。

  只想说说我感觉到的一些优点,对于不对,大家也可以和我讨论:

  首先是异步交互,用户感觉不到页面的提交,当然也不等待页面返回。这是使用了ajax技术的页面给用户的第一感觉。

  其次是响应速度快,这也是用户强烈体验。

  然后是与我们开发者相关的,复杂ui的成功处理,一直以来,我们对b/s模式的ui不如c/s模式ui丰富而苦恼。现在由于ajax大量使用js,使得复杂的ui的设计变得更加成功。

  最后,ajax请求的返回对象为xml文件,这也是一个潮流,就是web service潮流一样。易于和web service结合起来。

  好了,闲话少说,让我们转入正题吧。

  我们的第一个例子是基于servlet为后台的一个web应用。

  二、基于servletajax
 
  这是一个很常见的ui,当用户在第一个选择框里选择zhejiang时,第二个选择框要出现zhejiang的城市;当用户在第一个选择框里选择jiangsu时,第二个选择框里要出现jiangsu的城市。

  首先,我们来看配置文件web.xml,在里面配置一个servlet,跟往常一样:

 <web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 xsi:schemalocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
 <servlet>
 <servlet-name>selectcityservlet</servlet-name>
 <servlet-class>com.stephen.servlet.selectcityservlet</servlet-class>
 </servlet>
 
 <servlet-mapping>
 <servlet-name>selectcityservlet</servlet-name>
 <url-pattern>/servlet/selectcityservlet</url-pattern>
 </servlet-mapping>
 
 </web-app>

  然后,来看我们的jsp文件:

 <!doctype html public "-//w3c//dtd html 4.01 transitional//en">
 <html>
 <head>
 <title>myhtml.html</title>
 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="this is my page">
 
 <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
 
 </head>
 <script type="text/javascript">
 function getresult(stateval) {
       var url = "servlet/selectcityservlet?state="+stateval;
       if (window.xmlhttprequest) {
               req = new xmlhttprequest();
       }else if (window.activexobject) {
               req = new activexobject("microsoft.xmlhttp");
       }
       if(req){
               req.open("get",url, true);
               req.onreadystatechange = complete;
               req.send(null);
       }
 }
 function complete(){
       if (req.readystate == 4) {
               if (req.status == 200) {
                       var city = req.responsexml.getelementsbytagname("city");
                       file://alert(city.length);
                       var str=new array();
                       for(var i=0;i<city.length;i++){
                               str[i]=city[i].firstchild.data;
                       }
                       file://alert(document.getelementbyid("city"));
                       buildselect(str,document.getelementbyid("city"));
               }
       }
 }
 function buildselect(str,sel) {
       sel.options.length=0;
       for(var i=0;i<str.length;i++) {
               sel.options[sel.options.length]=new option(str[i],str[i])
       }
 }
 </script>
 <body>
 <select name="state" onchange="getresult(this.value)">
       <option value="">select</option>>
       <option value="zj">zehjiang</option>>
       <option value="zs">jiangsu</option>>
 </select>
 <select id="city">
   <option value="">city</option>
 </select>
 </body>
 </html>

  第一眼看来,跟我们平常的jsp没有两样。仔细一看,不同在js里头。

  我们首先来看第一个方法:getresult(stateval),在这个方法里,首先是取得xmlhttprequest;然后设置该请求的url:req.open("get",url, true);接着设置请求返回值的接收方法:req.onreadystatechange = complete;该返回值的接收方法为——complete();最后是发送请求:req.send(null);

  然后我们来看我们的返回值接收方法:complete(),这这个方法里,首先判断是否正确返回,如果正确返回,用dom对返回的xml文件进行解析。关于dom的使用,这里不再讲述,请大家参阅相关文档。得到city的值以后,再通过buildselect(str,sel)方法赋值到相应的选择框里头去。
 
  最后我们来看看servlet文件:

 import java.io.ioexception;
 import java.io.printwriter;
 
 import javax.servlet.servletexception;
 import javax.servlet.http.httpservlet;
 import javax.servlet.http.httpservletrequest;
 import javax.servlet.http.httpservletresponse;
 
 /**
  * @author administrator
  *
  * todo to change the template for this generated type comment go to
  * window - preferences - java - code style - code templates
  */
 public class selectcityservlet extends httpservlet {
 
 
   public selectcityservlet() {
           super();
   }
 
   public void destroy() {
           super.destroy();
   }
 
   public void doget(httpservletrequest request, httpservletresponse response)
                   throws servletexception, ioexception {
           response.setcontenttype("text/xml");
           response.setheader("cache-control", "no-cache");
           string state = request.getparameter("state");
           stringbuffer sb=new stringbuffer("<state>");
           if ("zj".equals(state)){
                   sb.append("<city>hangzhou</city><city>huzhou</city>");
           } else if("zs".equals(state)){
                   sb.append("<city>nanjing</city><city>yangzhou</city><city>suzhou</city>");
           }
           sb.append("</state>");
           printwriter out=response.getwriter();
           out.write(sb.tostring());
           out.close();
   }
 }

  这个类也十分简单,首先是从request里取得state参数,然后根据state参数生成相应的xml文件,最后将xml文件输出到printwriter对象里。

  到现在为止,第一个例子的代码已经全部结束。是不是比较简单?我们进入到第二个实例吧!这次是基于jspajax的一个应用。

  三、基于jspajax

   这个例子是关于输入校验的问题,我们知道,在申请用户的时候,需要去数据库对该用户性进行唯一性确认,然后才能继续往下申请。
 
  这种校验需要访问后台数据库,但又不希望用户在这里提交后等待,当然是ajax技术大显身手的时候了。

  首先来看显示ui的jsp:

 <!doctype html public "-//w3c//dtd html 4.01 transitional//en">
 <html>
 <head>
 <title>check.html</title>
 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="this is my page">
 
 <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
 
 </head>
 <script type="text/javascript">
  var http_request = false;
  function send_request(url) {//初始化、指定处理函数、发送请求的函数
   http_request = false;
   file://开始初始化xmlhttprequest对象
   if(window.xmlhttprequest) { file://mozilla 浏览器
  http_request = new xmlhttprequest();
  if (http_request.overridemimetype) {//设置mime类别
   http_request.overridemimetype('text/xml');
  }
   }
   else if (window.activexobject) { // ie浏览器
  try {
   http_request = new activexobject("msxml2.xmlhttp");
  } catch (e) {
   try {
    http_request = new activexobject("microsoft.xmlhttp");
   } catch (e) {}
  }
   }
   if (!http_request) { // 异常,创建对象实例失败
  window.alert("不能创建xmlhttprequest对象实例.");
  return false;
   }
   http_request.onreadystatechange = processrequest;
   // 确定发送请求的方式和url以及是否同步执行下段代码
   http_request.open("get", url, true);
   http_request.send(null);
  }
  // 处理返回信息的函数
   function processrequest() {
       if (http_request.readystate == 4) { // 判断对象状态
           if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
               alert(http_request.responsetext);
           } else { file://页面不正常
               alert("您所请求的页面有异常。");
           }
       }
   }
  function usercheck() {
   var f = document.form1;
   var username = f.username.value;
   if(username=="") {
  window.alert("the user name can not be null!");
  f.username.focus();
  return false;
   }
   else {
  send_request('check1.jsp?username='+username);
   }
  }
 
 </script>
 <body>
  <form name="form1" action="" method="post">
 user name:<input type="text" name="username" value="">&nbsp;
 <input type="button" name="check" value="check" onclick="usercheck()">
 <input type="submit" name="submit" value="submit">
 </form>
 </body>
 </html>

  所有的js都跟上一个例子一样,不同的只是对返回值的操作,这次是用alert来显示:alert(http_request.responsetext);

  我们来看处理逻辑jsp:

 <&#37;@ page contenttype="text/html; charset=gb2312" language="java" errorpage="" &#37;>
 <&#37;
 string username= request.getparameter("username");
 if("educhina".equals(username)) out.print("用户名已经被注册,请更换一个用户名。");
 else out.print("用户名尚未被使用,您可以继续。");
 &#37;>

  非常简单,先取得参数,然后作处理,最后将结果打印在out里。
  我们的第三个例子仍然以这个唯一性校验为例子,这次结合struts开发框架来完成ajax的开发。

  四、基于strutsajax

  首先,我们仍然是对struts应用来做配置,仍然是在struts-config,xml文件里做配置,如下:

 <action type="com.ajax.checkaction"
     scope="request" path="/ajax/check">
     <forward name="success" path="/check.jsp"/>
 </action>


  跟普通的struts应用的配置一样,只是没有actionform的配置。

  下面是action类:

 package com.ajax;
 
 import java.io.printwriter;
 
 import javax.servlet.http.httpservletrequest;
 import javax.servlet.http.httpservletresponse;
 
 import org.apache.struts.action.action;
 import org.apache.struts.action.actionform;
 import org.apache.struts.action.actionforward;
 import org.apache.struts.action.actionmapping;
 import org.apache.struts.action.dynaactionform;
 
 /**
  * @author administrator
  *
  * todo to change the template for this generated type comment go to
  * window - preferences - java - code style - code templates
  */
 public class checkaction extends action
 {
  public final actionforward execute(actionmapping mapping, actionform form,
           httpservletrequest request,
           httpservletresponse response)
   throws exception
   {
  system.out.println("haha...............................");
  string username= request.getparameter("username");
  system.out.println(username);
  string retn;
  if("educhina".equals(username)) retn = "can't use the same name with the old use,pls select a difference...";
  else retn = "congraducation!you can use this name....";
  printwriter out=response.getwriter();
           out.write(retn);
           out.close();
  return mapping.findforward("success");
   }
  public static void main(string[] args)
  {
  }
 }

  我们可以看到里面的逻辑跟上例中servlet里的逻辑一样。最后,我们来看看jsp:

 <!doctype html public "-//w3c//dtd html 4.01 transitional//en">
 <html>
 <head>
 <title>check.html</title>
 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="this is my page">
 
 <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
 
 </head>
 <script type="text/javascript">
  var http_request = false;
  function send_request(url) {//初始化、指定处理函数、发送请求的函数
   http_request = false;
   file://开始初始化xmlhttprequest对象
   if(window.xmlhttprequest) { file://mozilla 浏览器
  http_request = new xmlhttprequest();
  if (http_request.overridemimetype) {//设置mime类别
   http_request.overridemimetype('text/xml');
  }
   }
   else if (window.activexobject) { // ie浏览器
  try {
   http_request = new activexobject("msxml2.xmlhttp");
  } catch (e) {
   try {
    http_request = new activexobject("microsoft.xmlhttp");
   } catch (e) {}
  }
   }
   if (!http_request) { // 异常,创建对象实例失败
  window.alert("不能创建xmlhttprequest对象实例.");
  return false;
   }
   http_request.onreadystatechange = processrequest;
   // 确定发送请求的方式和url以及是否同步执行下段代码
   http_request.open("get", url, true);
   http_request.send(null);
  }
  // 处理返回信息的函数
   function processrequest() {
       if (http_request.readystate == 4) { // 判断对象状态
           if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
               alert(http_request.responsetext);
           } else { file://页面不正常
               alert("您所请求的页面有异常。");
           }
       }
   }
  function usercheck() {
   var f = document.forms[0];
   var username = f.username.value;
   if(username=="") {
  window.alert("the user name can not be null!");
  f.username.focus();
  return false;
   }
   else {
  send_request('ajax/check.do?username='+username);
   }
  }
 
 </script>
 <body>
  <form name="form1" action="" method="post">
 user name:<input type="text" name="username" value="">&nbsp;
 <input type="button" name="check" value="check" onclick="usercheck()">
 <input type="submit" name="submit" value="submit">
 </form>
 </body>
 </html>

  我们可以看到,jsp基本是一样的,除了要发送的url:ajax/check.do?username='+username。

  最后,我们来看一个基于strutsajax的复杂一些的例子,如果不用ajax技术,ui的代码将十分复杂。

  五、一个复杂的实例

  这是一个比较复杂的级联:一共八个列表框,三个下拉框。从第一个列表框里选择到第二个列表框里后,第一个选择框里的选项是第二个列表框的选择;然后,在第一个选择框里选择以后,与选择值关联的一些选项出现在第三个列表框里。从第三个列表框里选择选项到第四个列表框里,同样,第二个选择框的选项也是第四个列表框的选项;如果对第二个选择框进行选择后,与选择值关联的一些选项出现在第六个列表框里,依次类推……

  这个ui的逻辑就比较复杂,但使用了ajax使得我们实现起来就简单多了,这个例子我们除了使用action类,还要用到pojo类和business类,然后我们扩展的话,可以通过business类和数据库连接起来。

  我们还是先看配置文件:

 <action type="com.ajax.selectaction"
     scope="request" path="/ajax/select">
     <forward name="success" path="/select.jsp"/>
 </action>

   然后看看action类:

 /*
 /**
  * title : base dict class
  * description : here description is the function of class, here maybe multirows
  * copyright: copyright (c) 2004
  * @company freeborders co., ltd.
  * @goal feng       
  * @version     1.0
  */
 
 package com.ajax;
 
 import java.io.printwriter;
 import java.util.list;
 
 import javax.servlet.http.httpservletrequest;
 import javax.servlet.http.httpservletresponse;
 
 import org.apache.struts.action.action;
 import org.apache.struts.action.actionform;
 import org.apache.struts.action.actionforward;
 import org.apache.struts.action.actionmapping;
 
 /**
  * @author administrator
  *
  * todo to change the template for this generated type comment go to
  * window - preferences - java - code style - code templates
  */
 public class selectaction extends action
 {
  public final actionforward execute(actionmapping mapping, actionform form,
           httpservletrequest request,
           httpservletresponse response)
   throws exception
   {
  response.setcontenttype("text/xml");
        response.setheader("cache-control", "no-cache");
        string type = request.getparameter("type");
        string id = request.getparameter("id");
        system.out.println(id);
        stringbuffer sb=new stringbuffer("<select>");
        sb.append("<type>"+type+"</type>");
        
        list list = new selectbusiness().getdata(id);
        for(int i=0;i<list.size();i++)
        {
         selectform sel = (selectform)list.get(i);
         sb.append("<text>"+sel.gettext()+"</text><value>"+sel.getvalue()+"</value>");
        }
 
        sb.append("</select>");
        printwriter out=response.getwriter();
        out.write(sb.tostring());
        out.close();
        system.out.println(sb.tostring());
  return mapping.findforward("success");
   }
  public static void main(string[] args)
  {
  }
 }
 
  pojo类和business类:
 package com.ajax;
 /**
  * @author administrator
  *
  * todo to change the template for this generated type comment go to
  * window - preferences - java - code style - code templates
  */
 public class selectform
 {
  private string text;
  private string value;
 
  /**
   * @return returns the text.
   */
  public string gettext()
  {
   return text;
  }
  /**
   * @param text the text to set.
   */
  public void settext(string text)
  {
   this.text = text;
  }
  /**
   * @return returns the value.
   */
  public string getvalue()
  {
   return value;
  }
  /**
   * @param value the value to set.
   */
  public void setvalue(string value)
  {
   this.value = value;
  }
  public static void main(string[] args)
  {
  }
 }
 
 
 package com.ajax;
 
 import java.util.arraylist;
 import java.util.list;
 
 /**
  * @author administrator
  *
  * todo to change the template for this generated type comment go to
  * window - preferences - java - code style - code templates
  */
 public class selectbusiness
 {
  public list getdata(string id)
  {
   arraylist list = new arraylist();
   for(int i=1;i<6;i++)
   {
  selectform form = new selectform();
  form.settext(id+i);
  form.setvalue(id+i);
  list.add(form);
   }
   return list;
  }
 
  public static void main(string[] args)
  {
  }
 }

下一页


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons