課程需要,寫了一個簡單的Ajax資料存取操作,後台用的是Jsp,資料庫是Mysql...
1. Functions.js
代碼
var xmlHttp
/*讀取資料*/
function getUserInfo(uid)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("您的瀏覽器不支援AJAX!");
return;
}
var url="data.jsp";
url=url+"?uid="+uid;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
/*儲存資料*/
function saveUserInfo(uid)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("您的瀏覽器不支援AJAX!");
return;
}
var url="savedata.jsp";
var info="postdate..";
var postdate="uid="+uid+"&info="+info;
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert("data posted!");
}
};
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(postdate);
}
/*建立Request對象*/
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch(e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
2. data.jsp
代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*" %>
<%@ page import="mysqlcont.mysql"%>
<%@ page import="java.sql.*"%>
<%!
public static mysql sql = new mysql();
%>
<%
String uid = request.getParameter("uid").trim();
int id = Integer.parseInt(uid);
sql.select("select info from tablename where id="+id);
ResultSetMetaData meta = sql.rs.getMetaData();
while (sql.rs.next()) {
out.println(sql.rs.getString(1));
}
%>;
//說明:mysqlcont.mysql類就是另一篇隨筆《Java操作Mysql執行個體》中的類
3. savedata.jsp
代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*" %>
<%@ page import="mysqlcont.mysql"%>
<%@ page import="java.sql.*"%>
<%!
public static mysql sql = new mysql();
%>
<%
String uid = request.getParameter("uid").trim();
String info = request.getParameter("info").trim();
int id = Integer.parseInt(uid);
sql.update("update tablename set cloname='"+info+"' where id="+id);
out.println("update succeed!");
%>; //說明:mysqlcont.mysql類就是另一篇隨筆《Java操作Mysql執行個體》中的類
4. main.jsp
<html>
<head>
<script type="text/javascript" src="Functions.js"></script>
</head>
<body> <input type=text id="uid"> <input type=text id="info">
<input type=button id="save" onClick=saveUserInfo(document.getElementById('uid').id)> <input type=button id="read" onClick=getUserInfo(document.getElementById('uid').id)> </body>
</html>
End....