酷笔记 > JSON中文在线手册 > JQuery 获取json数据$.getJSON方法的实例代码
前台:
代码如下:
 function SelectProject() {
            var a = new Array;
            var r = window.showModalDialog('SelProject.aspx', a, "dialogWidth=1000px; dialogHeight=600px; resizable: yes");
            if (typeof (r) != 'undefined') {
                var arr = r.split(";");
                $("#hidProjectInnerID").val(arr[0]);
                $("#txtProjectNo").val(arr[1]);
                $.getjson("../Handler/GetProjectInfor.ashx", { key: "PaymentStatement", InnerID: $("#hidProjectInnerID").val() },
                        function (json) {
                            $("#labFinalCustomer").text(json.finalclient);
                            $("#labOrderNo").text(json.orderno);
                            var strDeviceTr = "";
                            $.each(json.workinghours, function (i, item) {
                                strDeviceTr += "<tr><td><lable name="infor"> " + item.description + "</lable> </td>";
                                strDeviceTr += "<td>   </td>";
                                strDeviceTr += " <td><lable name="infor"> " + item.hoursdays + "</lable></td>";
                                strDeviceTr += "<td>  0.8</td>";
                                strDeviceTr += "<td><lable name="infor"> " + item.workinghour + " </lable></td>";
                                strDeviceTr += "<td>  0.8</td>";
                                strDeviceTr += "<td><lable name="infor"> " + item.workinghour + "</lable></td>";
                                strDeviceTr += "<td>  </td>";
                                strDeviceTr += "</tr>";
                            });
                            $("#infor").append(strDeviceTr);
                        });
            }
        }

 ashx
代码如下:
string innerid = CommonClass.Request.GetRequest<string>("InnerID", "");
            string key = CommonClass.Request.GetRequest<string>("key", "");
            string result = "";
            if (key == "StockOutApp" && innerid != "")
            {
                result = StockOutApp(innerid);
                context.Response.Write(result);
            }
            else if (key == "PaymentStatement" && innerid != "")
            {
                result = PaymentStatement(innerid);
                context.Response.Write(result);
            }
#region 结算单信息
        public string PaymentStatement(string _innerid)
        {
            try
            {
                string sql = @"select InnerID,pFinalClient,pOrderNo from se_ProjectMain where InnerID='" + _innerid + "'";
                DataTable dt = SqlShift.GetDataTable(sql);
                if (!CommonClass.DTRow.CheckDtIsEmpty(dt))
                {
                    StringBuilder json = new StringBuilder();
                     json.Append(""innerid":""+dt.Rows[0]["InnerID"].ToString()+""");
                     json.Append(","finalclient":"" + dt.Rows[0]["pFinalClient"].ToString() + """);
                     json.Append(","orderno":"" + dt.Rows[0]["pOrderNo"].ToString() + """);
                    json.Append(","workinghours":" + GetWorkingHours(_innerid));
                    return "{" + json.ToString().Trim(',') + "}";
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                AppLog.Write("项目获取异常![异常信息:" + ex.Message + "]", AppLog.LogMessageType.Info);
                return string.Empty;
            }
        }
        public string GetWorkingHours(string _innerid)
        {
            try
            {
                string sql = @"select InnerID, wDescription,wWorkingHour,wHours_Days from se_ProjectWorkingHour where wProjectID='" + _innerid + "'";
                DataTable dt = SqlShift.GetDataTable(sql);
                if (!CommonClass.DTRow.CheckDtIsEmpty(dt))
                {
                    StringBuilder json = new StringBuilder();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        json.Append("{");
                        json.Append(""innerid":"" + dt.Rows[0]["InnerID"].ToString() + """);
                        json.Append(","description":"" + dt.Rows[0]["wDescription"].ToString() + """);
                        json.Append(","workinghour":"" + dt.Rows[0]["wWorkingHour"].ToString() + """);
                        json.Append(","hoursdays":"" + dt.Rows[0]["wHours_Days"].ToString() + """);
                        json.Append("},");
                    }
                    return "[" + json.ToString().Trim(',') + "]";
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                AppLog.Write("项目获取异常![异常信息:" + ex.Message + "]", AppLog.LogMessageType.Info);
                return string.Empty;
            }
        }
        #endregion 

通过jquery的$.getJSON做一个跨域ajax请求试验

jquery提供了$.getJSON的方法,让我们可以实现跨域ajax请求,但jqueryAPI上的内容实在太少,如何用$.getJSON,请求网站应该返回怎样的数据库才能让$.getJSON获取到,下面就用一个实际例子来说明下。

后端是用php的,以下代码主要实现的一个功能就是提供一个预约登记的接口,需要传入的数据分别有:用户姓名、联系电话和地址 
/*预约登记 执行 接口*/ 

代码如下:
/*预约登记 执行 接口*/ 
case "yuyue_interface": 
$name = trim($_GET['name']); 
$phone = trim($_GET['phone']); 
$addr = trim($_GET['addr']); 
$dt = date("Y-m-d H:i:s"); 
$cb = $_GET['callback']; 
if($name == "" || $name == NULL){ 
echo $cb."({code:".json_encode(1)."})"; 
}elseif($phone == "" || $phone == NULL){ 
echo $cb."({code:".json_encode(2)."})"; 
}elseif($addr == "" || $addr == NULL){ 
echo $cb."({code:".json_encode(3)."})"; 
}else{ 
$db->execute("insert into tb_yuyue (realname,telphone,danwei,dt,ischeck) values ('$name','$phone','$addr','$dt',0)"); 
echo $cb."({code:".json_encode(0)."})"; 
} 
exit; 
break; 

接着就是前端的处理了

代码如下:
$(document).ready(function(){ 
//以下3个为预约登记需要的参数 
var name = "name"; //varchar类型,长度最多为8位(4个汉字) 
var phone = "phone"; //varchar类型,长度为11位 
var addr = "addr"; //varchar类型,长度最多为500位(250个汉字) 
$.getJSON("Http://请求网站地址/data.php?ac=yuyue_interface&name="+name+"&phone="+phone+"&addr="+addr+"&callback=?", function(data){ 
if(data.code==1){ 
//自定义代码 
alert("姓名不能为空"); 
}else if(data.code==2){ 
//自定义代码 
alert("手机不能为空"); 
}else if(data.code==3){ 
//自定义代码 
alert("所在单位不能为空"); 
}else{ 
//自定义代码 
alert("预约成功"); 
} 
}); 
}); 
需要注意的是,在后端php代码里,必须把传递进来的“ &callback=? ”也输出来,如: 

代码如下:
$cb = $_GET['callback']; 
echo $cb."({code:".json_encode(4)."})"; 
以上就是一个简单的$.getJSON试验,通过这个试验,我们可以学到如何用$.getJSON,也能学到如何做一个接口让别人跨域请求。