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

JQuery的getJSON方法,对于后台是aspx页面,应该如何返回什么格式的数据,相关资料甚是寥寥。经一番艰苦尝试,总算成功。现贴示例如下:


1. 发送请求的WebForm1.aspx

  1. <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="WebForm1.aspx.cs"Inherits="Benq.Flower.WebAdmin.Module.WebForm1"%>
  2. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <htmlxmlns="http://www.w3.org/1999/xhtml">
  4. <headrunat="server">
  5. <title></title>
  6. <scriptsrc="../javascript/jquery-1.2.3.pack.js"type="text/javascript"language="javascript"></script>
  7. <scripttype="text/javascript"language="javascript">
  8. functiongetData()
  9. {
  10. $.getJSON("WebForm2.aspx?jsoncallback=?",
  11. function(data)
  12. {
  13. $.each(data.items,function(i,item)
  14. {
  15. $("<div></div>")
  16. .text(item.title)
  17. .css("color",item.color)
  18. .appendTo($("#listBox"));
  19. });
  20. }
  21. );
  22. }
  23. </script>
  24. </head>
  25. <body>
  26. <formid="form1"runat="server">
  27. <div>
  28. <inputid="Button1"type="button"value="clicktogetJson"onclick="javaScript:getData();"/>
  29. </div>
  30. <divid="listBox">
  31. </div>
  32. </form>
  33. </body>
  34. </html>

2. 提供数据的WebForm2.aspx
  1. publicpartialclassWebForm2:System.Web.UI.Page
  2. {
  3. protectedvoidPage_Load(objectsender,EventArgse)
  4. {
  5. stringcallback=Request.QueryString["jsoncallback"];
  6. stringdata="{\"title\":\"RecentUploadstaggedcat\",\"link\":\"http://www.sina.com.cn\",\"items\":[{\"title\":\"Russell003\",\"color\":\"red\"},{\"title\":\"Cat[07.04.11]\",\"color\":\"yellow\"}]}";
  7. stringresult=string.Format("{0}({1})",callback,data);
  8. Response.Expires=-1;
  9. Response.Clear();
  10. Response.ContentEncoding=Encoding.UTF8;
  11. Response.ContentType="application/json";
  12. Response.Write(result);
  13. Response.Flush();
  14. Response.End();
  15. }
  16. }

注意返回数据的格式 string.Format("{0}({1})",data)

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...