一、post.html
<!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>
<title>Jquery_Ajax_post请求</title>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#divPost").click(function(){
$.post("post.ashx",{CId:$("#columnId").val()},function(data){
//[{"id":"28","Title":"一级栏目(1)"},{"id":"29","Title":"一级栏目(1)"}]
$('#showPost ul').html("");
for(var i=0;i<data.length;i++)
{
var li = $("<li></li>").html(data[i].Title);
$("#showPost ul").append(li);
}
},"json");
});
});
</script>
</head>
<body>
<div>栏目Id:<input id="columnId" type="text"/></div>
<div id="divPost">点击:【Jquery_Ajax_post请求】</div>
<div id="showPost"><ul></ul></div>
</body>
</html>
二、post.ashx
<%@ WebHandler Language="C#" Class="post" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class post : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
SqlConnection conn = new SqlConnection("server=.;database=LTArticle;uid=sa;pwd=;");
conn.Open();
String CId = context.Request.Form["CId"];
SqlCommand com = new SqlCommand("select id,Title from LT_Article where ColumnId=" + CId, conn);
SqlDataReader sdr = com.ExecuteReader();
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
writer.WriteStartArray(); // [
while (sdr.Read())
{
writer.WriteStartObject(); // {
for (int i = 0; i < sdr.FieldCount; i++)
{
writer.WritePropertyName(sdr.GetName(i).Trim()); //行的列名
writer.WriteValue(sdr[i].ToString());
}
writer.WriteEndObject(); // }
}
writer.WriteEndArray(); // ]
context.Response.Write(sw.GetStringBuilder().ToString());
}
public bool IsReusable {
get {
return false;
}
}
}