使用Get for ajax调用给我500错误

时间:2014-09-03 05:19:05

标签: jquery asp.net ajax get webmethod

我使用POST调用[web方法],但是当我“获取”数据时,我正在尝试使用GET。

使用Post作品。 使用GET给我一个500错误。

这是对我的[web方法]的主要jquery调用:

        $.ajax({
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            url: 'Cloud/Feed.aspx/GetNextFrames2',
            data: '{ test: "hime"}',

这是我的测试[网络方法]。

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetNextFrames2(string test)
{
    return 'test'
}

如果我没有传递任何参数,我将使用GET没有错误。 一旦添加参数,我就会得到500内部错误。

我使用过wireshark和Fiddler,但我看不到任何有用的东西。

这显然是使用参数。所以,至少我已经确定了错误的位置。

我已经尝试将直接附加的参数传递给url:

myurl?PAR = TESTME ...

但仍然是同样的错误。

我还能尝试什么?

由于

3 个答案:

答案 0 :(得分:4)

问题在于查询字符串中的值。该值应在引号内。以下代码正常运作。

$.ajax({
            type: 'GET',
            contentType:'application/json',
            dataType: 'json',
            cache:false,
            url: "TestWebMathod.aspx/GetNextFrames2?test='hime'",
            error: function (error) {
                alert(error.responseText)
            },
            success: function (result) {
                alert(result.d)

            }

        });

另请查看error.responseText以了解确切的异常消息。这有助于解决错误。

答案 1 :(得分:2)

Ajax GET请求不应该具有Content-type,因为它们没有任何实体主体。

供参考:Do I need a content type for http get requests?

尝试

$.ajax({
        type: 'GET',
        dataType: 'JSON',
        url: "Cloud/Feed.aspx/GetNextFrames2?test='hime'",

其中任何一个都应该起作用

答案 2 :(得分:1)

以上关于GET contentType的评论是正确的 WebMethods 需要 - see this detailed post on why

所以真的,除非你做POST,恕我直言,让事情与WebMethods一起工作只是一件痛苦的事。 如果方法有一个参数(它会炸弹),我甚至无法使用GET,所以如果有人可以让它工作,那么就是勇敢的!请注意,即使是使用GET的链接示例也包含一个参数...不确定使用的内容是否为真(该文章的日期 2007 )。

所以,如果你必须(根据上面的答案更新):

    $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "Cloud/Feed.aspx/GetNextFrames2",
            //data: {"test": "foo"}, // GET -> Cloud/Feed.aspx/GetNextFrames2?test=foo
            data: {"test": "'foo'"}, //value now in quotes
            ...

的WebMethod:

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public static string GetNextFrames2(string test)
    {
        //Should now work based on answer above

        //Yes, this is FUBAR, but technically feasible (no need for params in method)
        //var query = HttpContext.Current.Request.QueryString;

        //now do what you need to do with your querystring data 
        // re: that's where your data is in GET ($.get)

        ....           
    }

其他令人敬畏的笔记:

  • 如果您有FriendlyUrls,则必须发表评论 AutoRedirectMode = RedirectMode.Permanent中的RouteConfig - > FriendlyUrlSettings - 因为它完成了所说的内容并将.aspx重定向到友好的网址" ...是的,包括以上内容......

希望这会有所帮助,也许会让你(而不是)想到WebAPI:)


更新摘要

好吧,上面显示的答案是将string括在引号中 - 所以它似乎(强烈地)键入参数。如果是int

  • 如果$ .get数据:{ "test": 55 }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public static string GetNextFrames2(int test)
    {
      ...