簡介
在 client 端,有些功能藉由非同步方式取得 JSON 資料。如果想要搜尋特定資料,該如何做呢?
範例:搜尋 JSON 物件
關鍵字
- jQuery.grep()
- JSON
// 匿名物件
var person = { pid: 'A123456789' };
// 匿名物件轉為 JSON 字串
var params = JSON.stringify( person );
$.ajax({
type: "POST",
url: "../../WebService.asmx/FindPerson", // WEB SERVICE
data: params, // 參數
contentType: "application/json; charset=utf-8", // 參數格式
dataType: "json", // 回傳格式
success: function(response) {
// 將 WEB SERVICE 回傳的字串轉為物件
var jsonObj = $.parseJSON(response.d);
// 使用 chrome 按 F12 選擇 console 即可看到結果
console.log("Hello, I am " + jsonObj.name);
} // ajax 執行成功
, failure: function(msg) { } // ajax 執行失敗
,error: function(msg) { } // ajax 執行發生錯誤
});
// WEB SERVICE
<WebMethod(True)> _
Public Function FindPerson(ByVal pid As String) As String
// DB 取出 Person 物件資料(附註DataTable轉Object可參考LINQ)
Dim pObj AS Person = db.SelectPerson(pid)
// 將物件序列化為字串
Return New JavaScriptSerializer().Serialize( pObj )
End Function
// 物件
Class Person
Public name As String
End Class