利用XMLHTTP无刷新添加数据(2)

http://www.itjxue.com  2015-08-06 23:22  来源:未知  点击次数: 

XMLHTTP来实现Form的Method=Post.

ClientPost.htm
<script language="JavaScript">
function AddDataPost(sUserId,sUserName)
{
/*
*--------------- AddDataPost(sUserId,sUserName) -----------------
* AddDataPost(sUserId,sUserName)
* 功能:通过XMLHTTP添加数据.相当于Form的Method=Post.
* 参数:sUserId,字符串,发送条件.
* 参数:sUserName,字符串,发送条件.
* 实例:AddDataPost(document.all.userid.value,document.all.username.value);
* author:wanghr100(灰豆宝宝.net)
* update:2004-5-30 14:46
*--------------- AddDataPost(sUserId,sUserName) -----------------
*/
var oBao = new ActiveXObject("Microsoft.XMLHTTP");
//特殊字符:+,%,&,=,?等的传输解决办法.
//Update:2004-6-1 12:22
//escape(sUserId),escape(sUserName);
sUserId = escape(sUserId);
sUserName = escape(sUserName);
var userInfo = "userid="+sUserId+"&username="+sUserName;
oBao.open("POST","Server.asp",false);
oBao.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
oBao.send(userInfo);
//清空输入框数据.
document.all.userid.value="";
document.all.username.value="";
//服务器端处理返回的是经过escape编码的字符串.
alert(unescape(oBao.responseText))
}
</script>
<input type="button" onclick="AddDataPost(document.all.userid.value,document.all.username.value)" value="AddDataPost"><br>
userid:<input type="text" name="userid"><br>
username:<input type="text" name="username">

Server.asp 服务器端处理.
<% @Language="JavaScript" %>
<%
function OpenDB(sdbname)
{
/*
*--------------- OpenDB(sdbname) -----------------
* OpenDB(sdbname)
* 功能:打开数据库sdbname,返回conn对象.
* 参数:sdbname,字符串,数据库名称.
* 实例:var conn = OpenDB("database.mdb");
* author:wanghr100(灰豆宝宝.net)
* update:2004-5-12 8:18
*--------------- OpenDB(sdbname) -----------------
*/
var connstr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="+Server.MapPath(sdbname);
var conn = Server.CreateObject("ADODB.Connection");
conn.Open(connstr);
return conn;
}
var sResult = "";
var oConn = OpenDB("data.mdb");
//相当于Form的Method=Post.
//相当于Form的Method=Post.
//特殊字符:+,%,&,=,?等的传输解决办法.客户端传输过来是经过escape编码的.
//所以服用器端应该先unescape解码.
//Update:2004-6-1 12:22
//unescape(Request.Form("userid")).....
var userid = unescape(Request.Form("userid"));
var username = unescape(Request.Form("username"));
sResult = "userid:"+userid+"\nusername:"+username+"\n 添加成功."
var sql = "Insert into users(userid,username)Values('"+userid+"','"+username+"')";
oConn.Execute(sql);
Response.Write(escape(sResult));
%>

数据库设计
data.mdb
表users.
字段
id 自动编号
userid 文本
username 文本

表:users 数据:
id userid username
1 wanghr100 灰豆宝宝.net

(责任编辑:IT教学网)

更多

推荐Javascript/Ajax文章