Ajax 互動中,從伺服器端回傳的資料型別有 xml、html、script、json、jsonp、text 等。本文以 JSON 為例,說明前端如何用 jQuery 處理三種常見結構。伺服器端採用 Json.NET 序列化 ArrayList、Hashtable、List<> 等位構。
下載 Json.NET 後加入引用:.NET 2.0 以上版本用 DotNet 資料夾下的 Newtonsoft.Json.dll,2.0 版本則用 DotNet20 資料夾下的檔案,然後在使用的頁面引入 using Newtonsoft.Json;。
接著新增 Web 服務檔 ProductService.asmx,並记得取消 [System.Web.Script.Services.ScriptService] 的註解,否則前端無法以 JSON 呼叫。
[WebMethod]
public string getProductInfoToJson(int productID)
{
SQLCMD = new SqlCommand("select id,name,price from dbo.productTest where id=@id", SQLConnect);
SQLCMD.CommandType = System.Data.CommandType.Text;
SQLCMD.Parameters.AddWithValue("@id", productID);
SQLConnect.Open();
SqlDataReader reader = SQLCMD.ExecuteReader();
Hashtable HTresult = new Hashtable();
while (reader.Read())
{
HTresult.Add("id", reader["id"]);
HTresult.Add("name", reader["name"]);
HTresult.Add("price", reader["price"]);
}
reader.Close();
SQLConnect.Close();
return JsonConvert.SerializeObject(HTresult);
}
$("#ShowInfo").click(function () {
var selectValue = $("#DropDownListCourseID").val();
$.ajax({
type: "POST",
url: "ProductService.asmx/getProductInfoToJson",
data: "{productID:" + selectValue + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var result = jQuery.parseJSON(msg.d);
$("#resultInfo").append(result.id + result.name + result.price + "<br/>");
}
});
});
這種結構最簡單,直接用 result.屬性名 取值即可。
[WebMethod]
public string GetProductList(string KeyWord) {
SQLCMD = new SqlCommand("getProductList", SQLConnect);
SQLCMD.CommandType = CommandType.StoredProcedure;
SQLCMD.Parameters.Add(new SqlParameter("@nameKeyWords", SqlDbType.NVarChar, 30));
SQLCMD.Parameters["@nameKeyWords"].Value = KeyWord;
SQLConnect.Open();
SqlDataReader reader = SQLCMD.ExecuteReader();
ArrayList ProductList = new ArrayList();
while (reader.Read()) { ProductList.Add(reader["name"].ToString()); }
reader.Close();
SQLConnect.Close();
return ProductList.Count > 0 ? JsonConvert.SerializeObject(ProductList) : "";
}
前端拿來做即時搜尋建議:
var suggestList = $('<ul class="autocomplete"></ul>').hide().insertAfter("#search #search-text");
$("#search-text").keyup(function () {
var textString = "{KeyWord:'" + $("#search #search-text").attr("value") + "'}"
$.ajax({
type: "POST",
url: "ProductService.asmx/GetProductList",
data: textString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
suggestList.empty();
var objData = jQuery.parseJSON(data.d);
$.each(objData, function (index, term) {
$("<li></li>").text(term).appendTo(suggestList);
});
suggestList.show();
}
});
});
一維清單只需一層 each。
[WebMethod]
public string GetBrandNameByKeyword(string Keyword)
{
SQLCMD = new SqlCommand("BrandInfo_Get_BrandName_UserInputKeyWord", SQLConnect);
SQLCMD.CommandType = CommandType.StoredProcedure;
SQLCMD.Parameters.Add(new SqlParameter("@KeyWord", SqlDbType.NVarChar, 10));
SQLCMD.Parameters["@KeyWord"].Value = Keyword;
Hashtable BrandNameInfo;
List<Hashtable> BrandNameInfoCollection = new List<Hashtable>();
SQLConnect.Open();
using (SqlDataReader reader = SQLCMD.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
BrandNameInfo = new Hashtable();
BrandNameInfo.Add("BrandName", reader["BrandName"].ToString());
BrandNameInfo.Add("BrandChineseName", reader["BrandChineseName"].ToString());
BrandNameInfo.Add("nameAbbreviation", reader["nameAbbreviation"].ToString());
BrandNameInfoCollection.Add(BrandNameInfo);
}
SQLConnect.Close();
return JsonConvert.SerializeObject(BrandNameInfoCollection);
}
SQLConnect.Close();
return null;
}
}
$.ajax({
type: "POST",
url: "ProductService.asmx/GetReceiverAddressInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var resultCollection = jQuery.parseJSON(msg.d);
$.each(resultCollection, function (index, item) {
var AddressInfo = [
'<input type="radio" name="ReceiveAddress" class="address" value="', item.id, '"/> ',
'<label class="vtip" title="<font size=3><b>收件人:</b> ', item.ReceiverName,
'</br><b>聯繫號碼:</b> ', item.ReceiverPhoneNo,
'</br><b>詳細地址:</b> ', item.DetailsAddress,
'</font>">', item.NoticeWords, '</label></br>'
].join('');
});
}
});
這是最常見的形態:外層 each 跑每一筆記錄,內層用 item.屬性名 取出各欄位。
jQuery 1.4.1 加入了 jQuery.parseJSON(json),定義是「接受一個格式良好的 JSON 字串,回傳對應的 JavaScript 物件」。相對於早期直接 eval,它安全得多,也讓處理伺服器端產生的 JSON 變得可靠。
一、用 parseJSON 前先確認 msg.d。ASMX 服務會把結果包在 d 屬性裡(這是為了防範特定 XSS 攻擊而加的包裝),所以一定要 parseJSON(msg.d) 而非 parseJSON(msg)。若改用 ashx 或 Web API 就沒有這層。
二、資料拼接要轉義。範例中把字串拼成 HTML,若欄位內容來自使用者,請先轉義或用 .text() 設定文字,避免 XSS。
三、Hashtable 序列化後的鍵名大小寫會照原樣保留。前端取值時務必與後端完全一致,這類「明明有資料卻是 undefined」的問題多半源自大小寫不符。