时间:2021-07-01 10:21:17 帮助过:9人阅读
- <br>getHellobyAjax: function(callabckFun) { <br>$.ajax({ <br>type: "GET", <br>url: "WebService.asmx/HelloWorld", <br>//contentType: "application/json; charset=utf-8", <br>//data:"{}", <br>cache: false, <br>dataType: "json", <br>success: function(msg) { <br>if (callabckFun) { <br>callabckFun(msg); <br>} <br>else { <br>alert("Not exists callback function."); <br>} <br>}, <br>error: function(obj, message) { <br>alert(message); <br>} <br>}); <br> <br>服务端,WebService的代码为: <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>[WebMethod] <br>[ScriptMethod(ResponseFormat = ResponseFormat.Json)] <br>public string HelloWorld() { <br>return "Hello World"; <br>} <br> <br>使用Fiddler跟踪,发现客户端调用服务器方法后,服务器返回的数据为XML格式。Why? 明明自己已经在方法属性上指明返回json,但是系统却还是我行我素照常返回XML呢? <br>到此,大家的眼睛都是雪亮的。海内外的网友一致指出.NET 3.5平台是需要检查contentType参数的,于是将上面代码中的代码注释去除,重新运行。这时又出现error错误。用Fiddler一查,发现是服务器返回了500错误。具体错误为: <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>{"Message":"试图使用 GET 请求调用方法“HelloWorld”,但不允许这样做。","StackTrace":" 在 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"} <br> <br>可是,按理说,我已经在web.config文件中对WebService做了相应的配置,为什么服务器还是不允许使用GET方式调用呢?无奈,将UseHttpGet属性加上,并设置其为true,再祭出Fiddler一查,OK,服务器返回了json格式的数据。 <br><br>再一看微软的代码注释,有如下一段,正好解释了上面的错误提示: <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>// true if the method is invoked by using the HTTP GET command; false if the <br>// method is invoked by using the HTTP POST command. The default is false. <br> <br>那么为什么Web.config已经允许使用GET,却不起作用呢?这只能解释为:Web.config文件中的配置只是配置允许WebService接收Get请求,具体到每一个方法时,还必须要配置该方法的调用方式才行(如有错误,请指出。谢谢!!)。 <br><strong>有人回复: <br></strong>将ws的scriptmethod那句改为:[System.Web.Script.Services.ScriptService] <br>js中启用content type <br>文章出处:www.cnblogs.com/jizhong</li><li> </li><li> </li></ol></pre></li></ol></pre></li></ol></pre>