您的位置:首页 > Web前端 > JQuery

c# 一般处理程序(Jquery ajax调用)

2014-12-10 10:50 323 查看
一般处理程序代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace WebApplication25
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string jsoncallback = context.Request.QueryString["jsoncallback"];
context.Response.Clear();
context.Response.Charset = "utf-8";
context.Response.Buffer = true;
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = "application/json";
context.Response.Write(jsoncallback + "(" + GetJsonData(context) + ")");
context.Response.Flush();
context.Response.End();
}
private string GetJsonData(HttpContext context)
{
string jsonString = string.Empty;
string StudentNamePrefix = "姓名";
//获取从页面传来的参数
if (context.Request.QueryString["StudentNamePrefix"] != null)
StudentNamePrefix = context.Request.QueryString["StudentNamePrefix"];
DataTable dt = new DataTable();
dt.Columns.Add("StudentID", typeof(int));
dt.Columns.Add("StudentName", typeof(string));
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["StudentID"] = (i + 1);
dr["StudentName"] = StudentNamePrefix + (i + 1);
dt.Rows.Add(dr);
}
jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
return jsonString;
}

public bool IsReusable
{
get
{
return false;
}
}
}
}
Jquery ajax调用(跨域调用)

<script type="text/javascript">
$(function () {
var url = 'http://172.19.10.176/Handler1.ashx?jsoncallback=?';
$.ajax({
type: "get",
url: url,
data: { StudentNamePrefix: '学生' },
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (error) {}
});
});
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息