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

来源:互联网 发布:淘宝联盟助手机机器人 编辑:程序博客网 时间:2024/06/02 00:21

一般处理程序代码

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>




0 0