利用ajax和JSP技术实现网页中表单的局部刷新(只刷新表单数据,而不刷新整个页面)

前端之家收集整理的这篇文章主要介绍了利用ajax和JSP技术实现网页中表单的局部刷新(只刷新表单数据,而不刷新整个页面)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在web开发中有时有局部刷新的需求,这样做的好处是克服了页面整体刷新对网络速度受限的情况。


1.MysqL数据表如下(简单举例):

表名:stu_info

stuId int PK NN

stuName varchar(45) NN

stuDesc varchar(45)


2.新建wk.jsp,代码如下:

<span style="color:#330033;"><%@ page contentType="text/html; charset=utf-8" %>
<head>  
    <Meta http-equiv=Content-Type content="text/html; charset=utf-8">  
    </head>  
    <script language="javascript">  
      
    var XMLHttpReq;  
        //创建XMLHttpRequest对象         
        function createXMLHttpRequest() {  
            if(window.XMLHttpRequest) { //Mozilla 浏览器  
                XMLHttpReq = new XMLHttpRequest();  
            }  
            else if (window.ActiveXObject) { // IE浏览器  
                try {  
                    XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");  
                } catch (e) {  
                    try {  
                        XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");  
                    } catch (e) {}  
                }  
            }  
        }  
        //发送请求函数  
        function sendRequest() {  
            createXMLHttpRequest();  
            var url = "ajax.jsp";  
            XMLHttpReq.open("GET",url,true);  
            XMLHttpReq.onreadystatechange = processResponse;//指定响应函数  
            XMLHttpReq.send(null);  // 发送请求  
        }  
        // 处理返回信息函数  
        function processResponse() {  
            if (XMLHttpReq.readyState == 4) { // 判断对象状态  
                if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息  
                    DisplayHot();  
                    setTimeout("sendRequest()",1000);  
                } else { //页面不正常  
                    window.alert("您所请求的页面有异常。");  
                }  
            }  
        }  
        function DisplayHot() {  
      	  var yan1 = XMLHttpReq.responseXML.getElementsByTagName("id");
          var yan = XMLHttpReq.responseXML.getElementsByTagName("name");
          var yan2 = XMLHttpReq.responseXML.getElementsByTagName("description");
          	var ta = "";
            for(var i=0;i<yan.length;i++){
            	var id = yan1[i].firstChild.nodeValue;
             	var name = yan[i].firstChild.nodeValue;  
             	var desc = yan2[i].firstChild.nodeValue;
             ta+="<tr align=left><td><table><td width=100>"+id+"</td><td width=200>"+name+"</td><td width=200>"+desc+"</td></table></td></tr>"; 
           // document.getElementById(res).innerHTML = name;    
          //  res = res +i.toString();  
           }
            document.getElementById("res").innerHTML = ta;
} 
      
      
    </script>  
      
    <body onload =sendRequest() >
    <table style="BORDER-COLLAPSE: collapse" borderColor=#111111 cellSpacing=0 cellPadding=0 width=400    bgColor=#f5efe7 border=0> 
   <TR>  
       <TD align=middle bgColor=#dbc2b0 height=19 colspan="3"><B>学生信息</B> </TD>  
    </TR> 
    <tr><td>学号</td><td>姓名</td><td>备注</td></tr>
    </table>
    <table border=1 width=400>
    
     <div id="res"></div> 
   </table>
    </body>  
    </table></span>

3.新建Conn.jsp,代码如下:

<span style="color:#330033;"></pre><p><pre name="code" class="html"><%@ page contentType="text/html; charset=utf-8" import="java.sql.*,javax.naming.Context,javax.naming.InitialContext" 
errorPage=""%> 
<%!Connection conn = null; 
Statement stmt = null; 
ResultSet rs = null; 

public void jspInit() { 
try { 
Class.forName("com.MysqL.jdbc.Driver"); 
//建立连接 
conn = DriverManager.getConnection( 
 "jdbc:MysqL://192.168.1.106:3306/acsystem","ouyang","ouyang"); 
 //if(conn!=null){
 	//System.out.println("connect success");
 //}
//Context initCtx = new InitialContext(); 
//Context ctx = (Context) initCtx.lookup("java:comp/env"); 
//获取连接池对象 
//Object obj = (Object) ctx.lookup("jdbc/javasky"); 
//类型转换 
//javax.sql.DataSource ds = (javax.sql.DataSource) obj; 
//conn = ds.getConnection(); 
stmt = conn.createStatement(); 
} catch (Exception ex) { 
System.out.println(ex.toString()); 
} 
} 

public void Exec(String sql) { 
jspInit(); 
try { 
stmt.executeUpdate(sql); 
} catch (Exception e) { 
System.out.print(e.toString()); 
} 
} 

public ResultSet getRs(String sql) throws sqlException { 
jspInit(); 
try { 
rs = stmt.executeQuery(sql); 
return rs; 
} catch (Exception e) { 
System.out.print(e); 
return null; 
} 
} 

public ResultSet executeQuery(String sql) throws Exception { 
jspInit(); 
try { 
sql = new String(sql.getBytes("GBK"),"utf-8"); 
stmt = conn.createStatement( 
java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); 
rs = stmt.executeQuery(sql); 
} catch (sqlException ex) { 
System.out.println("sql.executeQuery:" + ex.getMessage()); 
} 
return rs; 
} 

public String getS(String Str) { 
try { 
byte b[] = Str.getBytes("ISO-8859-1"); 
Str = new String(b,"UTF-8"); 
} catch (Exception ee) { 
ee.printStackTrace(); 
} 
return Str; 
}%> </span>

 
 

4.新建ajax.jsp,代码如下:

<span style="color:#330033;"><%@ page contentType="text/html; charset=utf-8" import="java.sql.*,java.util.*" errorPage="" %> 
<%@ include file="Conn.jsp" %> 
<% 
  try{ 
  ResultSet rs=getRs("select * from stu_info order by stuId asc"); 
  StringBuffer content=new StringBuffer(""); 
  response.setContentType("text/xml;charset=UTF-8"); 
  response.setHeader("Cache-Control","no-cache"); 
  //out.println("<?xml version=\"1.0\"   encoding=\"UTF-8\" ?>"); 
  out.println("<response>"); 
    while(rs.next()){ 
    String id=rs.getString("stuId"); 
    int stuId = Integer.parseInt(id);
    String stuName=rs.getString("stuName"); 
     String stuDesc=rs.getString("stuDesc"); 
    System.out.println(stuId);
     //out.println("<content>"); 
     out.println("<id>" +stuId+ "</id>"); 
     out.println("<name>" +stuName+ "</name>"); 
     out.println("<description>" +stuDesc+ "</description>"); 
     //out.println("</content>"); 
     } 
   out.println("</response>"); 
   out.close(); 
  } 
catch(Exception e){ 
      e.printStackTrace(); 
   } 
%> </span>

5.把上述3个页面放在项目同一个文件夹下,运行wk.jsp 即可得到表单stu_info的数据。

(PS:这里为简单举例,样式什么的可以自行添加修改。有错误欢迎指正。)

原文链接:https://www.f2er.com/ajax/163034.html

猜你在找的Ajax相关文章