前台:
<script language="javascript">
function Getson(pid, SelectId) {
$.ajax({
type:"post",
async:false,
url:"xx.ashx",
data:"pid=" + pid,
dataType:"json",
success:function(data) {
var html = "";
if (data != "") {
var temp = eval(data);
for (var i = 0; i < temp.length; i++) {
html += "<option value='" + temp[i].id + "'>" + temp[i].name + "</option>";
}
}
else {
html = "<option value='0'>暂无</option>";
}
// for (var i = 0; i < temp.length; i++) {
// html += "<option value='" + temp[i].code + "' ";
// if(temp[i].code==SelectId){
// html += "selected='selected' ";
// }
// html += ">" + temp[i].name + "</option>";
// }
$("#" + SelectId).html(html);
}
});
}
</script>
ashx处理程序:
using System;
using System.Web;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using mynamespace;
public class Handler : IHttpHandler {
UseSqlData N =null;
DataTable ar2 ;
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//数据库操作
N = new UseSqlData();
string pid = "0";
if(context.Request["pid"]!=null&&context.Request["pid"]!=""){
pid=context.Request["pid"];
}
string strSQL="SELECT id,name FROM xxxx where parentID ="+pid+" order by orderid ";
context.Response.Write("[");
string tempstr="";//使用stringbufferd最好
ar2 = N.GetDataTable(strSQL,"f2");
if(ar2!=null){
for( int i = 0 ;i < ar2.Rows.Count ;i ++){
tempstr=tempstr+"{";
tempstr=tempstr+"\"id\":\""+ar2.Rows[i][0]+"\",";
tempstr=tempstr+"\"name\":\""+ar2.Rows[i][1]+"\"";
tempstr=tempstr+"},";
}
}
if(tempstr!="") tempstr=tempstr.Substring(0,tempstr.Length-1);
context.Response.Write(tempstr);
context.Response.Write("]");
N =null;
}
public bool IsReusable {
get {
return false;
}
}
}
还可以C#自带的方法转化json格式