JQuery的getJSON方法,对于后台是aspx页面,应该如何返回什么格式的数据,相关资料甚是寥寥。经一番艰苦尝试,总算成功。现贴示例如下:
1. 发送请求的WebForm1.aspx
- <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="WebForm1.aspx.cs"Inherits="Benq.Flower.WebAdmin.Module.WebForm1"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunat="server">
- <title></title>
- <scriptsrc="../javascript/jquery-1.2.3.pack.js"type="text/javascript"language="javascript"></script>
- <scripttype="text/javascript"language="javascript">
- functiongetData()
- {
- $.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>
- <formid="form1"runat="server">
- <div>
- <inputid="Button1"type="button"value="clicktogetJson"onclick="javaScript:getData();"/>
- </div>
- <divid="listBox">
- </div>
- </form>
- </body>
- </html>
2. 提供数据的WebForm2.aspx
- publicpartialclassWebForm2:System.Web.UI.Page
- {
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- stringcallback=Request.QueryString["jsoncallback"];
- stringdata="{\"title\":\"RecentUploadstaggedcat\",\"link\":\"http://www.sina.com.cn\",\"items\":[{\"title\":\"Russell003\",\"color\":\"red\"},{\"title\":\"Cat[07.04.11]\",\"color\":\"yellow\"}]}";
- stringresult=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();
- }
- }
注意返回数据的格式 string.Format("{0}({1})",data) 原文链接:https://www.f2er.com/json/290736.html