欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-06 17:30:50
jquery大家都经常用,以前用的时候没有注意什么。最近本人在使用jquery通过httpget方式调用webservice时,却发现服务端并非如人所愿返回json数据,而...
jquery大家都经常用,以前用的时候没有注意什么。最近本人在使用jquery通过httpget方式调用webservice时,却发现服务端并非如人所愿返回json数据,而是返回错误提示:parserror。
如今问题被顺利解决,下面是解决过程

首先看客户端使用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)\r\n 在 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请求,具体到每一个方法时,还必须要配置该方法的调用方式才行(如有错误,请指出。谢谢!!)。
有人回复:
将ws的scriptmethod那句改为:[system.web.script.services.scriptservice]
js中启用content type
文章出处:www.cnblogs.com/jizhong