从前三步走过来以后,个人感觉有那么点意思了,呵呵,貌似是可以小效果了,恩,感觉不错。哈哈,抽根得胜烟,乐和乐和。
突然头脑中冒出一个念头,我这前几步只是简单的进行了异步提交了,如果我需要返回结果改怎么办呢?比如实现一个异步查询,那么我需要接受查询结果吧,这个结果该如何接收呢,Javascript它貌似不认识datatable啊什么的东西吧。
恩,不能得意,还要继续啊。首先来试着做一个查询,先写后端代码:
随意的在APP_CODE里写一个DB.CS(如果我的写法和习惯哪里不好或者不合格请园内众神指正,小弟在此谢过了)
Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
/// <summary>
///DB 的摘要说明
/// </summary>
public class DB
{
private static readonly string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
public DB()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public IList<Info> GetAll()
{
string str = "select user_id,user_name,user_favor from tb_user";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = str;
conn.Open();
IList<Info> list = new List<Info>();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Info i = new Info();
i.User_ID = rdr.GetInt32(0);
i.User_Name = rdr.GetString(1);
if (rdr.IsDBNull(2))
{
i.User_Favor = string.Empty;
}
else
{
i.User_Favor = rdr.GetString(2);
}
list.Add(i);
}
}
return list;
}
public void del(int id)
{
string str = "delete from tb_user where user_id="+id;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = str;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
额,上面没用参数化,随意写了一下。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
/// <summary>
///DB 的摘要说明
/// </summary>
public class DB
{
private static readonly string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
public DB()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public IList<Info> GetAll()
{
string str = "select user_id,user_name,user_favor from tb_user";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = str;
conn.Open();
IList<Info> list = new List<Info>();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Info i = new Info();
i.User_ID = rdr.GetInt32(0);
i.User_Name = rdr.GetString(1);
if (rdr.IsDBNull(2))
{
i.User_Favor = string.Empty;
}
else
{
i.User_Favor = rdr.GetString(2);
}
list.Add(i);
}
}
return list;
}
public void del(int id)
{
string str = "delete from tb_user where user_id="+id;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = str;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
然后是实体类,Info.CS
Code
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
///Info 的摘要说明
/// </summary>
public class Info
{
public Info()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public int User_ID
{
set;
get;
}
public string User_Name
{
set;
get;
}
public string User_Favor
{
set;
get;
}
}
另外就还是我在上一步中使用到的AJAX.JS了
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
///Info 的摘要说明
/// </summary>
public class Info
{
public Info()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public int User_ID
{
set;
get;
}
public string User_Name
{
set;
get;
}
public string User_Favor
{
set;
get;
}
}
Code
function CreateXMLHTTPRequest()
{
var xmlreq=null;
if(window.ActiveXObject)
{
xmlreq=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlreq=new XMLHttpRequest();
}
return xmlreq;
}
function TalkToServer(method,url,callback,contentType,content)
{
var req=CreateXMLHTTPRequest();
req.onreadystatechange=GetReadyStateHandler(req,callback,contentType);
req.open(method,url,true);
if(method=="POST")
{
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
req.send(content);
}
function GetReadyStateHandler(req,callback,contentType)
{
return function()
{
if(req.readyState==4 && req.status==200)
{
if(contentType=="Text")
{
callback(req.responseText);
}
if(contentType=="XML")
{
callback(req.responseXML);
}
}
}
}
其实到这一步时我还在考虑如何将C#中的数据结果传递到客户端,经过一番折腾终于得到了结果,需要序列化...
function CreateXMLHTTPRequest()
{
var xmlreq=null;
if(window.ActiveXObject)
{
xmlreq=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlreq=new XMLHttpRequest();
}
return xmlreq;
}
function TalkToServer(method,url,callback,contentType,content)
{
var req=CreateXMLHTTPRequest();
req.onreadystatechange=GetReadyStateHandler(req,callback,contentType);
req.open(method,url,true);
if(method=="POST")
{
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
req.send(content);
}
function GetReadyStateHandler(req,callback,contentType)
{
return function()
{
if(req.readyState==4 && req.status==200)
{
if(contentType=="Text")
{
callback(req.responseText);
}
if(contentType=="XML")
{
callback(req.responseXML);
}
}
}
}
那么来看异步提交的页面,Run.ASHX
Code
<%@ WebHandler Language="C#" Class="Run" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
public class Run : IHttpHandler {
DB db = new DB();
JavaScriptSerializer js = new JavaScriptSerializer();
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
if (context.Request.QueryString["del"] != null)
{
int id = Convert.ToInt32(context.Request.QueryString["id"].ToString());
db.del(id);
context.Response.Write(js.Serialize(db.GetAll()));
}
else
{
context.Response.Write(js.Serialize(db.GetAll()));
}
}
public bool IsReusable {
get {
return false;
}
}
}
在这里得知了一个新的词语:【json】
<%@ WebHandler Language="C#" Class="Run" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
public class Run : IHttpHandler {
DB db = new DB();
JavaScriptSerializer js = new JavaScriptSerializer();
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
if (context.Request.QueryString["del"] != null)
{
int id = Convert.ToInt32(context.Request.QueryString["id"].ToString());
db.del(id);
context.Response.Write(js.Serialize(db.GetAll()));
}
else
{
context.Response.Write(js.Serialize(db.GetAll()));
}
}
public bool IsReusable {
get {
return false;
}
}
}
此时按下不表我们以后在说。
最后就是如何在前端页面中使用了,在Default.aspx也中写如下代码
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<script type="text/javascript" src="AJAX.js"></script>
<script type="text/javascript" language="javascript">
function sendInfo()
{
TalkToServer("GET","Run.ashx",GetData,"Text",null);
}
function GetData(content)
{
var josn =eval(content);
var len=josn.length;
var tbl=document.getElementById("tblData");
for(var i=tbl.rows.length-1;i>0;i--)
{
tbl.deleteRow(i);
}
for(var i=0;i<len;i++)
{
var row=tbl.insertRow();
var cell=row.insertCell();
cell.innerText=josn[i].User_ID;
var cell=row.insertCell();
cell.innerText=josn[i].User_Name;
var cell=row.insertCell();
cell.innerText=josn[i].User_Favor;
var cell=row.insertCell();
cell.innerHTML='<input type="button" onclick="del('+josn[i].User_ID+');" value="删除" />';
}
}
function del(id)
{
TalkToServer("GET","Run.ashx?del=true&id="+id,GetData,"Text",null);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tblData" cellspacing="1" cellpadding="0">
<tr>
<th>
编号
</th>
<th>
姓名
</th>
<th>
爱好
</th>
<th>
</th>
</tr>
</table>
<div >
<input id="b" type="button" onclick="sendInfo();" value="确定" />
</div>
</div>
</form>
</body>
</html>
其中可以看到,在使用json对象是需要这样
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<script type="text/javascript" src="AJAX.js"></script>
<script type="text/javascript" language="javascript">
function sendInfo()
{
TalkToServer("GET","Run.ashx",GetData,"Text",null);
}
function GetData(content)
{
var josn =eval(content);
var len=josn.length;
var tbl=document.getElementById("tblData");
for(var i=tbl.rows.length-1;i>0;i--)
{
tbl.deleteRow(i);
}
for(var i=0;i<len;i++)
{
var row=tbl.insertRow();
var cell=row.insertCell();
cell.innerText=josn[i].User_ID;
var cell=row.insertCell();
cell.innerText=josn[i].User_Name;
var cell=row.insertCell();
cell.innerText=josn[i].User_Favor;
var cell=row.insertCell();
cell.innerHTML='<input type="button" onclick="del('+josn[i].User_ID+');" value="删除" />';
}
}
function del(id)
{
TalkToServer("GET","Run.ashx?del=true&id="+id,GetData,"Text",null);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tblData" cellspacing="1" cellpadding="0">
<tr>
<th>
编号
</th>
<th>
姓名
</th>
<th>
爱好
</th>
<th>
</th>
</tr>
</table>
<div >
<input id="b" type="button" onclick="sendInfo();" value="确定" />
</div>
</div>
</form>
</body>
</html>
var josn =eval(content);
然后就可以像使用普通对象那样子了,不过不知道我的初步理解是否正确。
我喜欢对象.属性 什么的形式,呵呵。
在这里有一点需要说的就是,使用C#中的自动序列化的方法时,传递的参数必须是可以进行迭代的,我当时尝试着传递了一个datatable进去,结果报错了,所以我做了泛型传进去。恩,需要考虑考虑了。