Jquery调用从ashx文件返回的jsonp格式的数据处理实例

开发环境:vs2010+jquery-1.4.min.js

解决问题:网上代码比较少,好多调试不通,返回数据不用json而用jsonp主要考虑解决跨域问题

开发步骤:打开VS2010,新建一web站点,保存位置选择D:\Website1;添加新项,选择一般处理程序,命名cmdHandler.ashx;添加新项,选择HTML页,命名为testAshx.htm;网上下载jquery-1.4.min.js拷贝到web站点中

项目相关代码和运行截图如下:

1、testAshx.htm代码如下:

<!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调用ashx文件返回的jsonp格式数据实例</title>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
</head>
<body>
    <div id="Div1"> </div>
    <div id="Div2"> </div>
    <div id="Div3"> </div>
    <div id="Div4"> </div>
    <script type="text/javascript" >
        //回调函数1
        function success_jsonpCallback11(data) {
            var $ul = $("<ul></ul>");
            $.each(data, function (i, v) {
                $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
            });
            $("#Div2").html($ul);
        }
        //回调函数2
        function success_jsonpCallback22(data) {
            var $ul = $("<ul></ul>");
            $.each(data, function (i, v) {
                $("<li/>").text(v["OrderID"] + " " + v["CustomerID"]).appendTo($ul)
            });
            $("#Div4").html($ul);
        }
        //页面加载完成后执行下面代码
        $(document).ready(function () {
            //读取Ashx文件中直接返回的字符串
            $.ajax({
                url: ‘cmdHandler.ashx‘,
                data: { StatusCode: 1 },
                dataType: "jsonp",
                jsonp: "jsonpcallback",
                success: function (data) {
                    var $ul = $("<ul></ul>");
                    $.each(data, function (i, v) {
                        $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
                    });
                    $("#Div1").html($ul);
                }
            });
            //读取Ashx文件中直接返回的字符串带回调函数名称
            $.ajax({
                type: "get",
                async: false,
                url: "cmdHandler.ashx",
                data: { StatusCode: 1 },
                dataType: "jsonp",
                jsonp: "jsonpcallback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
                jsonpCallback: "success_jsonpCallback1", //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
                success: function (json) {
                    //在此之前若没有定义回调函数success_jsonpCallback1则执行下面的代码
                    var $ul = $("<ul></ul>");
                    $.each(json, function (i, v) {
                        $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
                    });
                    $("#Div2").html($ul);
                },
                error: function () {
                    alert(‘fail‘);
                }
            });
            //读取Ashx文件中返回的数据库字符串
            $.ajax({
                type: "get",
                async: false,
                url: "cmdHandler.ashx",
                data: { StatusCode: 2 },
                dataType: "jsonp",
                jsonp: "jsonpcallback",
                success: function (json) {
                    var $ul = $("<ul></ul>");
                    $.each(json, function (i, v) {
                        $("<li/>").text(v["OrderID"] + " " + v["CustomerID"]).appendTo($ul)
                    });
                    $("#Div3").html($ul);
                },
                error: function () {
                    alert(‘fail‘);
                }
            });
            //读取Ashx文件中返回的数据库字符串带回调函数名称
            $.ajax({
                type: "get",
                async: false,
                url: "cmdHandler.ashx",
                data: { StatusCode: 2 },
                dataType: "jsonp",
                jsonp: "jsonpcallback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
                jsonpCallback: "success_jsonpCallback2", //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
                success: function (json) {
                    //在此之前若没有定义回调函数success_jsonpCallback2则执行下面的代码
                    var $ul = $("<ul></ul>");
                    $.each(json, function (i, v) {
                        $("<li/>").text(v["OrderID"] + " " + v["CustomerID"]).appendTo($ul)
                    });
                    $("#Div4").html($ul);
                },
                error: function () {
                    alert(‘fail‘);
                }
            });
            /* 回调函数写在末尾时候不起作用
            function success_jsonpCallback(data) {
                alert("测试成功");
            }
            */
    });
</script>
</body>
</html>

2、cmdHandler代码如下:

<%@ WebHandler Language="C#" Class="cmdHandler" %>

using System;
using System.Web;
//添加引用
using System.Data;
using System.Data.SqlClient;
using System.Text;

public class cmdHandler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string StatusCode = context.Request.QueryString["StatusCode"];
        switch (StatusCode)
        {
            case "1"://返回测试用的组合字符串
                context.Response.Write(getFormatString(context));
                break;
            case "2"://返回查询数据库得到的组合字符串
                context.Response.Write(GetDbString(context));
                break;
        }
    }
    #region 测试用的组合字符串
    public string getFormatString(HttpContext context)
    {
        string strReturn = "";
        string jsonp = context.Request["jsonpcallback"];
        string str = "[{\"id\":\"1\",\"name\":\"张三\"},{\"id\":\"2\",\"name\":\"李四\"}]";
        strReturn = jsonp + "(" + str + ")";
        return strReturn;
    }
    #endregion

    #region 查询数据库得到组合字符串
    public string GetDbString(HttpContext context)
    {
        string strReturn = "";
        string strConn = "server=.;database=northwnd;uid=sa;pwd=123456;";//数据库连接字符串
        string strFun = context.Request["jsonpcallback"];//传递参数
        StringBuilder strJsonData = new StringBuilder();//拼接json所有格式
        StringBuilder strJsonMsgData = new StringBuilder();//拼接json内容
        string sqlText = "select top 3 * from Orders";//查询数据表语句
        DataSet ds = new DataSet();
        SqlConnection mySqlConnection = new SqlConnection();
        mySqlConnection.ConnectionString = strConn;
        try
        {
            mySqlConnection.Open();
            SqlCommand mySqlCommand = new SqlCommand();
            mySqlCommand.CommandText = sqlText;
            mySqlCommand.Connection = mySqlConnection;
            SqlDataAdapter da = new SqlDataAdapter(mySqlCommand);
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                strJsonData.AppendFormat("{0}([", strFun);//json begin
                foreach (DataRow row in dt.Rows)//得到行集合
                {
                    strJsonMsgData.Append("{\"OrderID\"" + ":" + "\"" + row["OrderID"].ToString() + "\"" + ",\"CustomerID\"" + ":" + "\"" + row["CustomerID"].ToString() + "\"}" + ",");
                }
                strJsonData.Append(strJsonMsgData.ToString().TrimEnd(‘,‘));
                strJsonData.Append("])");//json end

                strReturn = strJsonData.ToString();
            }
            else
            {
                strJsonData.AppendFormat("{0}([", strFun);//json begin
                strJsonData.Append("])");//json end
                strReturn = strJsonData.ToString();
            }
        }
        catch
        {
        }
        finally
        {
            mySqlConnection.Close();
        }
        return strReturn;
    }
    #endregion

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

3、jquery-1.4.min.js文件不贴代码了,网上自己下,也可以使用更高版本的jquery.js文件

4、IE和火狐运行截图如下:

 

Jquery调用从ashx文件返回的jsonp格式的数据处理实例,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。