JQuery.getJSON 从aspx页面返回JSON数据

本文介绍了一个简单的C# Web应用程序如何通过JSONP(JSON with Padding)方式实现跨域数据请求。该示例中,服务器端使用C#接收前端发送的带有回调函数名的请求,并将JSON数据包裹在回调函数内返回。前端通过jQuery发起JSONP请求并处理服务器返回的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public partial class WebForm2 : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            string callback = Request.QueryString["jsoncallback"];  
            string data = "{\"title\": \"Recent Uploads tagged cat\",\"link\": \"http://www.sina.com.cn\",\"items\": [{\"title\": \"Russell 003\",\"color\": \"red\"},{\"title\": \"Cat [07.04.11]\",\"color\": \"yellow\"}]}";  
            string result = string.Format("{0}({1})", callback, data);  
            Response.Expires = -1;  
            Response.Clear();  
            Response.ContentEncoding = Encoding.UTF8;  
            Response.ContentType = "application/json";  
            Response.Write(result);  
            Response.Flush();  
            Response.End();  
        }  
    }  
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Benq.Flower.WebAdmin.Module.WebForm1" %>  
  
<!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 runat="server">  
    <title></title>  
  
    <script src="../javascript/jquery-1.2.3.pack.js" type="text/javascript" language="javascript"></script>  
  
    <script type="text/javascript" language="javascript">  
        function getData()  
        {  
            $.getJSON("WebForm2.aspx?jsoncallback=?",  
                function(data)  
                {  
                    $.each(data.items, function(i, item)  
                    {  
                        $("<div></div>")  
                            .text(item.title)  
                            .css("color", item.color)  
                            .appendTo($("#listbox"));  
                    });                      
                }  
          );  
  
        }  
    </script>  
  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>          
        <input id="Button1" type="button" value="click to get Json" onclick="javaScript:getData();" />  
    </div>  
    <div id="listbox">  
    </div>  
    </form>  
</body>  
</html>  

 

转载于:https://www.cnblogs.com/shiningrise/p/4796866.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值