Ajax简单易懂实例教程【原创】

jsp页面如下:

<%@ page contentType="text/html; charset=gb2312"%>

<html>
<head>
   <meta http-equiv=Content-Type content="text/html; charset=gb2312" />
   <title></title>
</head>

<body>
   <div id="body" style="padding-left: 8px">
    <CENTER>
          <form name="regForm" action="register.do" method="POST">
           <div style="width: 50%; float: left;">
            <p style="color: red; font-size: 14px; font-weight: bold;">
             &nbsp;
            </p>
            <dl>
             <dt class="logindt">
              用户名:
             </dt>
             <dd class="logindd">

              <input name="email" type="text" value="" class="input"
               οnchange="ajaxCheckEmail2();" maxlength="20"
               οnfοcus="lblEmail.innerText='';" />
              <label id="lblEmail" class="alert"></label>
              <br>
             </dd>
             </dl>
            
             <dl>
              <dl>
               得到的值:
              </dl>
              <dd>
              <input name="value" type="text" value=""/>
              </dd>            
             </dl>
          </form>      
    </CENTER>
   </div>

<script type="text/javascript">

var show = document.getElementById("lblEmail");
  
   //ajax方法  
   var str="";
   var xmlHttp;
function createXMLHttpRequest() {  
    try{
     if (window.ActiveXObject) {      
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     }else {    
     if (window.XMLHttpRequest) {  
      xmlHttp = new XMLHttpRequest();
     }
       }   
    }catch(e){
      alert("不能创建XMLHttpRequest对象实例,请重试");
    }  
}    
   //ajax所调用的方法
   function ajaxCheckEmail2(){
        var email=regForm.elements["email"].value;
           var show = document.getElementById("lblEmail");
            ajaxCheckEmail();
   }
  
function ajaxCheckEmail() {
     createXMLHttpRequest();   
   var email = document.getElementsByName("email")[0].value;   
   var url = "numAjax.do?email="+email;
   xmlHttp.open("POST", url, true);  
   xmlHttp.onreadystatechange = callback;
   xmlHttp.send(null);
}
  
function callback(){    
   if (xmlHttp.readyState == 4) {          
      str = xmlHttp.responseText;
        //alert(str);
    if (xmlHttp.status == 200) {   
       str = xmlHttp.responseText;
                 //alert("响应的值是"+str);
                 showMessage(str);               
       } else {
          show.innerText="";
       }  
     }
}
  
function showMessage(str) {
      document.getElementById("value").value = str;
}
</script>

</body>

</html>

 

处理通讯的action类,用的是struts1.2的action:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class numAjaxAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)throws java.io.IOException {
  
   String userId_1 = request.getParameter("email");
  
   String userId = "";
   String backValue = "";//返回的数据
   userId = new String(userId_1.getBytes("8859_1"),"GB2312");
  
   //连接数据库 开始
   try{
    Class.forName("com.mysql.jdbc.Driver");
    }
     catch(java.lang.ClassNotFoundException e)
    {
      System.err.print(e.getMessage());
    }
   String url="jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=utf-8";
   try {
    Connection conn=DriverManager.getConnection(url,"root","123456");
    String sql = " select action_name from t_pdm_action where action_code = "+userId;
   
    System.out.println("sql :"+sql);
   
    PreparedStatement prpdStmt = conn.prepareStatement(sql);
    ResultSet rs = prpdStmt.executeQuery();//收集到要的数据了
   
    if(rs.next()){
    
     backValue = rs.getString("action_name");
     System.out.println("backValue GB2312 :"+backValue);

    }
    rs.close();
    prpdStmt.close();
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }

   response.setContentType("text/xml;charset=UTF-8");
    response.getOutputStream().print(backValue);
    return null;   
  
}
}

action配置文件:

    <action
      input="/"
      path="/numAjax"
      type="com.me.user.numAjaxAction" />

 

搞定!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值