一聚教程网:一个值得你收藏的教程网站

热门教程

JQuery通过HttpGet调用WebService返回Json时“parserror”错误

时间:2022-06-25 04:04:27 编辑:袖梨 来源:一聚教程网

首先看客户端使用JQuery调用WebService的代码:

 

 代码如下 复制代码

 

        getHellobyAjax: function(callabckFun) {
            $.ajax({
                type: "GET",
                url: "WebService.asmx/HelloWorld",
                //contentType: "application/json; charset=utf-8",
                //data:"{}",
                cache: false,
                dataType: "json",
                success: function(msg) {
                    if (callabckFun) {
                        callabckFun(msg);
                    }
                    else {
                        alert("Not exists callback function.");
                    }
                },
                error: function(obj, message) {
                    alert(message);
                }
            });


 

服务端,WebService的代码为:

 

 代码如下 复制代码

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld() {
        return "Hello World";
    }
 

使用Fiddler跟踪,发现客户端调用服务器方法后,服务器返回的数据为XML格式。Why? 明明自己已经在方法属性上指明返回json,但是系统却还是我行我素照常返回XML呢?

到此,大家的眼睛都是雪亮的。海内外的网友一致指出.NET 3.5平台是需要检查contentType参数的,于是将上面代码中的代码注释去除,重新运行。这时又出现error错误。用Fiddler一查,发现是服务器返回了500错误。具体错误为:

 

 代码如下 复制代码
{"Message":"试图使用 GET 请求调用方法“HelloWorld”,但不允许这样做。","StackTrace":"   在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)rn   在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

 

可是,按理说,我已经在web.config文件中对WebService做了相应的配置,为什么服务器还是不允许使用GET方式调用呢?无奈,将UseHttpGet属性加上,并设置其为true,再祭出Fiddler一查,OK,服务器返回了json格式的数据。

 

再一看微软的代码注释,有如下一段,正好解释了上面的错误提示:

 

        //     true if the method is invoked by using the HTTP GET command; false if the
        //     method is invoked by using the HTTP POST command. The default is false.
 

那么为什么Web.config已经允许使用GET,却不起作用呢?这只能解释为:Web.config文件中的配置只是配置允许WebService接收Get请求,具体到每一个方法时,还必须要配置该方法的调用方式才行(如有错误,请指出。谢谢!!)。

热门栏目