2012年6月7日 星期四

AJAX 與 WEB SERVICE 溝通

開發簡介

  • AJAX 使用 jQuery 的 ajax 功能
  • WEB SERVICE 採用 VB.NET 撰寫

參考範例

  • 匿名物件的變數名稱pid與 WEB SERVICE 的參數名稱pid相同
  • 監看 javascript 執行過程或執行結果,請參考 CHROME DEVELOPER TOOL

前端程式碼

// 匿名物件
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

沒有留言:

張貼留言