Asp.Net+Jquery.Ajax详解4-$.getJSON

来源:岁月联盟 编辑:exp 时间:2012-08-06

jQuery.getJSON(url, [data], [callback])

通过 HTTP GET 请求载入 JSON 数据。

 

参数

url:为请求的url地址

data:待发送 Key/value 参数。

callback:载入成功时回调函数。

 

 jQuery.getJSON提供了回调函数(callback),该函数有三个参数:responseText,textStatus,XMLHttpRequest,分别代表请求返回的内容、请求状态和XMLHttpRequest对象。

[javascript] 
$.get("Data/GetServiceInfo.aspx",function(responseText,textStatus,XMLHttpRequest){  
 
//responseText:请求返回的内容   
 
//textStatus:请求状态:success、error、notmodified、timeout  
 
//XMLHttpRequest:XMLHttpRequest对象   
 
}); 

$.get("Data/GetServiceInfo.aspx",function(responseText,textStatus,XMLHttpRequest){

//responseText:请求返回的内容

//textStatus:请求状态:success、error、notmodified、timeout

//XMLHttpRequest:XMLHttpRequest对象

});


 

实例(vs2010):

客户端——

[html]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JqueryAjaxGetJson.aspx.cs" Inherits="JqueryAjaxTest.JqueryAjaxGetJson" %> 
 
<!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>Jquery Ajax Test</title> 
       <%--引入Jquery库--%> 
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
        $(function () { 
            //为按钮绑定事件 
            $("#TestGetJson").bind("click", GetJsonWithCallback); 
        
        }); 
 
 
        //测试getJSON,使用回调函数 
        //注意:get()方法提供了回调函数(callback), 
        //该函数有三个参数,分别代表请求返回的内容、请求状态和XMLHttpRequest对象 
        function GetJsonWithCallback(event) { 
 
            $.getJSON("Data/GetCity.aspx", { "resultType": "json" }, function (responseText, textStatus, XMLHttpRequest) { 
                $("#result").html("responseText.length:" + responseText.length + "<br/>" + "responseText[0].CityName:" + responseText[0].CityName); 
                 
            }); 
        } 
   
        </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     
        <input id="TestGetJson" type="button" value="测试jquery.getJSON" /> 
            
        <div id="result"> 
        </div> 
    </div> 
    </form> 
</body> 
</html> 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JqueryAjaxGetJson.aspx.cs" Inherits="JqueryAjaxTest.JqueryAjaxGetJson" %>

<!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>Jquery Ajax Test</title>
       <%--引入Jquery库--%>
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            //为按钮绑定事件
            $("#TestGetJson").bind("click", GetJsonWithCallback);
      
        });


        //测试getJSON,使用回调函数
        //注意:get()方法提供了回调函数(callback),
        //该函数有三个参数,分别代表请求返回的内容、请求状态和XMLHttpRequest对象
        function GetJsonWithCallback(event) {

            $.getJSON("Data/GetCity.aspx", { "resultType": "json" }, function (responseText, textStatus, XMLHttpRequest) {
                $("#result").html("responseText.length:" + responseText.length + "<br/>" + "responseText[0].CityName:" + responseText[0].CityName);
               
            });
        }
 
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <input id="TestGetJson" type="button" value="测试jquery.getJSON" />
          
        <div id="result">
        </div>
    </div>
    </form>
</body>
</html>

服务端——

[csharp] 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
 
namespace JqueryAjaxTest.Data 

    public partial class GetCity : System.Web.UI.Page 
    { 
        private string resultType = "json"; 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            //获取请求的参数  
            if (!String.IsNullOrEmpty(Request.QueryString["resultType"])) { 
 
                resultType = Request.QueryString["resultType"].ToLower()=="html" ? "html" : "json"; 
            } 
           string  html = GetResult(resultType); 
 
           //清空缓冲区  
           Response.Clear(); 
           //将字符串写入响应输出流  
           Response.Write(html); 
           //将当前所有缓冲的输出发送的客户端,并停止该页执行  
           Response.End(); 
        } 
 
        private string GetResult(string resultType) { 
            string result = ""; 
            if (resultType == "html") { 
 
               //返回的html  
                result = @"<ul><li id=""1"">北京</li><li id=""2"">天津</li></ul>"; 
            } 
            else if (resultType == "json") { 
                //返回的json数据  
                result = @" 
[{""pkid"":""0001"",""ProvinceId"":""BJ"",""CityName"":""北京"",""CityNameEn"":""Beijing"",""PostCode"":""010"",""isHotCity"":false}, 
 {""pkid"":""0002"",""ProvinceId"":""TJ"",""CityName"":""天津"",""CityNameEn"":""Tianjin"",""PostCode"":""022"",""isHotCity"":false}]"; 
                   
            } 
            return result; 
        } 
    } 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JqueryAjaxTest.Data
{
    public partial class GetCity : System.Web.UI.Page
    {
        private string resultType = "json";
        protected void Page_Load(object sender, EventArgs e)
        {
            //获取请求的参数
            if (!String.IsNullOrEmpty(Request.QueryString["resultType"])) {

                resultType = Request.QueryString["resultType"].ToLower()=="html" ? "html" : "json";
            }
           string  html = GetResult(resultType);

           //清空缓冲区
           Response.Clear();
           //将字符串写入响应输出流
           Response.Write(html);
           //将当前所有缓冲的输出发送的客户端,并停止该页执行
           Response.End();
        }

        private string GetResult(string resultType) {
            string result = "";
            if (resultType == "html") {

               //返回的html
                result = @"<ul><li id=""1"">北京</li><li id=""2"">天津</li></ul>";
            }
            else if (resultType == "json") {
                //返回的json数据
                result = @"
[{""pkid"":""0001"",""ProvinceId"":""BJ"",""CityName"":""北京"",""CityNameEn"":""Beijing"",""PostCode"":""010"",""isHotCity"":false},
 {""pkid"":""0002"",""ProvinceId"":""TJ"",""CityName"":""天津"",""CityNameEn"":""Tianjin"",""PostCode"":""022"",""isHotCity"":false}]";
                 
            }
            return result;
        }
    }
}
 

你可能会有疑问,什么是JSON?和XML有什么区别?

 

虽然XML已在不少应用程序中大显身手,但它并不是十全十美的,特别是遇到AJAX应用的时候,XMLHttpRequest会检查返回数据的MIME类型,如果是text/xml类型,XMLHttpRequest就会运行XML Parser来解析返回的文档,并在内存中构建出对应的DOM树,之后,你可以用JavaScript标准的DOM方法来操作DOM树。由于众所周知DOM的诟病,这显然不是有效率的方法。另外一个问题是,如果你想使用JavaScript对象而不是直接用XML数据的话,你还得自己遍历整个DOM树来创建相应对象。

 

于是JSON出现在我们面前。

 

JSON提供了一种更适合AJAX应用的标准数据交换格式。JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。

 作者;shan9liang