JQuery 獲取json數據$.getJSON方法的實例代碼

2022-05-17 14:44 更新
前臺部分:
代碼如下:
 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的方法,讓我們可以實現(xiàn)跨域ajax請求,但jqueryAPI上的內容實在太少,如何用$.getJSON,請求網站應該返回怎樣的數據庫才能讓$.getJSON獲取到,下面就用一個實際例子來說明下。

后端是用php的,以下代碼主要實現(xiàn)的一個功能就是提供一個預約登記的接口,需要傳入的數據分別有:用戶姓名、聯(lián)系電話和地址 
/*預約登記 執(zhí)行 接口*/ 

代碼如下:
/*預約登記 執(zhí)行 接口*/ 
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,也能學到如何做一個接口讓別人跨域請求。 
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號