gpt4 book ai didi

jquery - 为什么我无法使用 GET 向 WebMethod 发送参数?

转载 作者:行者123 更新时间:2023-12-01 04:58:21 25 4
gpt4 key购买 nike

我的 WebMethod 如下所示:

[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json, UseHttpGet=true)]
public List<Person> HelloWorld(string hello)
{
List<Person> persons = new List<Person>
{
new Person("Sarfaraz", DateTime.Now),
new Person("Nawaz", DateTime.Now),
new Person("Manas", DateTime.Now)
};
return persons;
}

我尝试使用 jQuery 调用此方法:

var params={hello:"sarfaraz"}; //params to be passed to the WebMethod
$.ajax
({
type: "GET", //have to use GET method
cache: false,
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: 'json',
url: "http://localhost:51519/CommentProviderService.asmx/HelloWorld",
processData: true,
success: onSuccess,
error: onError //it gets called!
});

但是这不起作用。它没有调用 onSuccess 回调,而是调用 onError,其中我使用 alert 作为:

alert(response.status + " | " + response.statusText + " | " + response.responseText + " | " + response.responseXML );

打印这个:

500 | Internal Server Error | {"Message":"Invalid web service call, missing value for parameter: \u0027hello\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary2 parameters)\r\n at
System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object
target, IDictionary
2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} | undefined

我不明白为什么会出现此错误。

如果我将 jQuery 调用更改为使用 POST 方法并设置 UseHttpGet=false ,那么效果很好。但我希望它能够与 GET 一起使用。需要修复什么?

最佳答案

HTTP GET 期望参数全部编码在 URL 中。

问题是你正在做 JSON.stringify在你的有效负载上。 jQuery.ajax实际上只是在寻找简单的字典,它可以变成一系列查询字符串参数。

所以如果你有一个像这样的对象:

{ name: "value" }

jQuery 会将其附加到 URL 的末尾,如下所示:

?name=value

使用 Firebug、Chrome 开发人员工具或 IE 开发人员工具检查传出 URL,我怀疑您会看到它的格式是 ASP.Net 无法转换的格式。

关于jquery - 为什么我无法使用 GET 向 WebMethod 发送参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12652999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com