使用 jQuery Ajax 将参数传递给 WebMethod

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/736058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:40:31  来源:igfitidea点击:

Passing parameter to WebMethod with jQuery Ajax

asp.netjqueryweb-servicesjsonparameters

提问by Briana Finney

I have a simple web method and ajax call and continue to recieve an error that saying that it can't convert a string to an IDictionary object???

我有一个简单的 web 方法和 ajax 调用,并继续收到一个错误,说它不能将字符串转换为 IDictionary 对象???

Here is the ajax call:

这是ajax调用:

var params = '{"ID":"' + rowid + '"}';
$.ajax({
  url: 'EDI.asmx/GetPartnerDetails',
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify(params),
  dataType: "json", //not json . let me try to parse
  success: function(msg, st) { . . . .

Here is the webMethod:

这是webMethod:

<WebMethod()> _
Public Function GetPartnerDetails(ByVal ID As String) As String

    'Dim objParam As IDictionary = CType(JsonConvert.DeserializeObject(ID), IDictionary)
    'Dim rowID As String = objParam("ID")

    Dim objController As New HealthComp.BLL.X12Partners.TradingPartnersController
    Dim objInfo As TradingPartnersInfo = objController.FetchByPartnerID(Int32.Parse(ID))

    Return JsonConvert.SerializeObject(objInfo)
End Function

Here is what I see from FireBug:

这是我从 FireBug 看到的:

Response Headers
Server: Microsoft-IIS/5.1
Date: Thu, 09 Apr 2009 21:43:59 GMT
jsonerror:true
Cache-Control:private
Content-Type:application/json; charset=utf-8
Content-Length:1331

响应头
服务器:Microsoft-IIS/5.1
日期:2009 年 4 月 9 日星期四 21:43:59 GMT
jsonerror:true
Cache-Control:private
Content-Type:application/json; 字符集=utf-8
内容长度:1331

POST: "{\"ID\":\"4\"}"

POST: "{\"ID\":\"4\"}"

RESPONSE:

回复:

{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections .Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":" at System.Web.Script.Serialization .ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain (Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject )\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer .Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest (HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler .GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services .RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType" :"System.InvalidOperationException"}

{"Message":"无法将 \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& ConvertObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain (Object o, Type type, JavaScriptSerializer serializer , Boolean throwOnError, Object& ConvertObject )\r\n 在 System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, JavaScriptSerializer serializer)\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize( JavaScriptSerializer 序列化器,字符串输入,类型类型,Int32 depthLimit)\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer .Deserialize[T](字符串输入)\r\n 在 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext 上下文,JavaScriptSerializer 序列化程序)\ r\n 在 System.Web.Script.Services.RestHandler .GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n 在 System.Web.Script.Services .RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType" :“System.InvalidOperationException”}GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n 在 System.Web.Script.Services .RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType" :"System.InvalidOperationException"}GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n 在 System.Web.Script.Services .RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType" :"System.InvalidOperationException"}

Anyone have any ideas about this? Thanks!!

有人对此有任何想法吗?谢谢!!

回答by Chris Brandsma

Quick item:

快速项目:

your variable params var params = '{ID:' + rowid + '}';is a string.

你的变量 params var params = '{ID:' + rowid + '}';是一个字符串。

So the line: data: JSON.stringify(params),is redundant (or it should be). Just set data: params,

所以这条线: data: JSON.stringify(params),是多余的(或者应该是)。刚设置data: params,

Next up, on your web method, you converting your result to a JSON string and returning that as a string. If you web method class has ScriptMethod attribute, you don't need to do that. Just return the data as the native type, and Asp.Net will do the conversion to JSON for you.

接下来,在您的 Web 方法中,您将结果转换为 JSON 字符串并将其作为字符串返回。如果您的 Web 方法类具有 ScriptMethod 属性,则不需要这样做。只需将数据作为本机类型返回,Asp.Net 就会为您完成到 JSON 的转换。

You might read the following articles: http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/

您可能会阅读以下文章:http: //elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

回答by XtraSimplicity

In addition to the above, it is worth checking to make sure that you aren't 'stringifying' the JSON array more than once.

除了上述内容之外,还值得检查以确保您没有多次“字符串化”JSON 数组。

I accidentally called JSON.stringify() on an array that had already been serialized, which threw a similar issue to the one the OP received.

我不小心在已经序列化的数组上调用了 JSON.stringify(),这引发了与 OP 收到的问题类似的问题。

i.e.

IE

var arr = JSON.stringify({ id: elementID, name: Name });
....
$.ajax({
...
data: JSON.stringify(arr),
...
});

In this instance, changing the arrvariable initialization to

在这种情况下,将arr变量初始化更改为

var arr = { id: elementID, name: Name };

resolved my issue. :)

解决了我的问题。:)