簡體   English   中英

使用jQuery Ajax將參數傳遞給WebMethod時出錯

[英]Passing parameter to WebMethod with jQuery Ajax getting error

我正在使用Web方法和Ajax調用,但無法通過參數正確地進行操作嗎?

我已經做了很多修復工作,但是還不能解決我的問題?

我需要通過字符串並讓我的Web方法返回數據表,為什么有必要將其作為json傳遞呢?

這是ajax調用:

var jsdata = '{category:' + category + '}';
var jstext = JSON.stringify(jsdata, null, 2);
$.ajax({
  type: "POST",
  url: "GIFacRequest.aspx/GetSubCategories",
  data: jstext ,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (dtSubCategory) {
        PopulateSubCategoryDD(dtSubCategory);
      },
      error: function (response) {
         $('body', document).html(response.responseText);
      }
  });

而我的網絡方法:

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static DataTable GetSubCategories(string category)
{
}

我得到的錯誤如下:

“消息”:“無法將類型\\ u0027System.String \\ u0027的對象轉換為類型\\ u0027System.Collections.Generic.IDictionary`2 [System.String,System.Object] \\ u0027”,“ StackTrace”:“在System.Web .Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o,Type type,JavaScriptSerializer serializer,Boolean throwOnError,Object&convertedObject)\\ r \\ n位於System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o,Type type,JavaScriptSerializer序列化器,在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer序列化器,字符串輸入,類型類型,Int32 depthLimit)處的布爾throwOnError,Object&convertObject)\\ r \\ n在System.Web.Script.Serialization.JavaScriptSerializer處。在System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext上下文,JavaScriptSerializer序列化器)處反序列化[T](String輸入)\\ r \\ n在System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData處) ,HttpContex t context)\\ r \\ n在System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)“,” ExceptionType“:” System.InvalidOperationException“

您的變量params var jsdata = '{category:' + category + '}'是一個字符串。

所以這行: JSON.stringify(jsdata, null, 2); ,是多余的(或者應該是)。 只需設置數據:jsdata,

嘗試使用此代碼

var jsdata = '{category:' + category + '}';
$.ajax({
  type: "POST",
  url: "GIFacRequest.aspx/GetSubCategories",
  data: jsdata ,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (dtSubCategory) {
        PopulateSubCategoryDD(dtSubCategory);
      },
      error: function (response) {
         $('body', document).html(response.responseText);
      }
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM