码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2014-05-28 09:21:49      阅读:509      评论:0      收藏:0      [点我收藏+]

标签:des   style   c   class   blog   code   

开发环境: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文件不贴代码了,到http://www.codesocang.com自己下载,也可以使用更高版本的jquery.js文件

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

bubuko.com,布布扣

文章来源:http://www.codesocang.com/jiaocheng/js/7701.html

 

Jquery调用从ashx文件返回的jsonp格式的数据处理实例,布布扣,bubuko.com

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

标签:des   style   c   class   blog   code   

原文地址:http://www.cnblogs.com/miaoqing/p/3755167.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!