2011-04-05 96 views
0

我正在嘗試使用Jquery驗證並調用web服務來驗證字段。但是,當我這樣做,我得到了Firebug的錯誤:JSON無效標籤

無效標籤 {「d」:假}

這裏是我的代碼,任何人可以幫助?

$("form").validate({ 
     //errorLabelContainer: $("#divErrors"), 

      rules: { 
       txtUserName: { 
        required: true, 
        minlength: 4, 
        maxlength: 20, 
        remote: function() { 
         var r = { 
          type: "POST", 
          url: "/Services/CDServices.asmx/CheckForUniqueUserName", 
          contentType: "application/json; charset=utf-8", 
          dataType: "json", 
          data: "{'strUserName':'" + $('input[name="txtUserName"]').val() + "'}" 
         } 
         return r; 
        } 
       } 

[WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public bool CheckForUniqueUserName(string strUserName) 
    { 
     return false; 
    } 

回答

1

讀了你的情況,你可以使用dataFilter功能「解包」你的結果,這樣的:

$("form").validate(
    //errorLabelContainer: $("#divErrors"), 
    rules: { 
    txtUserName: { 
     required: true, 
     minlength: 4, 
     maxlength: 20, 
     remote: function() { 
     var r = { 
      type: "POST", 
      url: "/Services/CDServices.asmx/CheckForUniqueUserName", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      data: "{'strUserName':'" + $('input[name="txtUserName"]').val() + "'}", 
      dataFilter: function (data, dataType) { 
      if (dataType == "json") { 
       var result = $.parseJSON(data); 
       if (result.d) { 
       return result.d; 
       } else { 
       return data; 
       } 
      } else { 
       return data; 
      } 
      } 
     } 
     return r; 
     } 
    } 
    } 
}); 
3

在ASP.NET中,服務器返回的數據的前綴返回.D。看看這個簡單的例子:

$.ajax({ 
    type: "POST", 
    url: "RSSReader.asmx/GetRSSReader", 
    data: "{}", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(msg) { 
     // Hide the fake progress indicator graphic. 
     $('#RSSContent').removeClass('loading'); 

     // Insert the returned HTML into the <div>. 
     $('#RSSContent').html(msg.d); 
    } 
    }); 

更多信息,http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

+0

什麼將是我的例子中返回.d值的正確語法? – user517406 2011-04-05 08:03:41