2011-10-15 61 views
2

我在asp.net一個簡單的Web服務,其確定輸入的參數是否有效:如何在jquery ajax調用中使用webservice的返回值?

[WebMethod] 
public bool IsValidNationalCode(string input) 
{ 
    return input.IsNationalCode(); 
} 

我的jQuery AJAX函數調用它從aspx頁面:

$('#txtNationalCode').focusout(function() { 
     var webMethod = "../PMWebService.asmx/IsValidNationalCode"; 
     var param = $('#txtNationalCode').val(); 
     var parameters = "{input:" + param + "}"; 

     $.ajax({ 
      type: "POST", 
      url: webMethod, 
      data: parameters, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (msg) { 
       if(msg.responseText == true) 
        $('#status').html("Valid"); 
       else { 
        $('#status').html("Invalid"); 
       } 
      }, 
      error: function() { 
       $('#status').html("error occured"); 
      } 
    }); 
}); 

但我不知道如何獲得webservice的返回值以顯示適當的消息。這裏if(msg.responseText == true)不起作用

回答

3

充分利用IsValidNationalCode方法靜態和在JavaScript中使用此:

success: function (msg) { 
    if (msg.d == true) 
     $('#status').html("Valid"); 
    else { 
     $('#status').html("Invalid"); 
    } 
} 

對於 「d」 的解釋請點擊此鏈接:Never worry about ASP.NET AJAX’s .d again

+0

謝謝,msg.d工作,如果返回類型將是html而不是json。我將returntype轉換爲'html',並且由msg.d工作 – Mostafa