这是网络服务
public class HelloWorld : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Hello()
{
return "Hello World";
}
}
这是javascript ajax代码
$(document).ready(function () {
$.ajax({
url: "Service/HelloWorld.asmx/Hello",
dataType: 'json',
type: 'POST',
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Success : :' + rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
});
获取错误
Excep:: Invalid JSON: <?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>Status:: OK
最佳答案
确保您在 web.config 的 Handler 部分下设置了 ScriptHandlerFactory。
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
有关更多信息,请查看以下链接:
http://www.asp.net/web-forms/tutorials/aspnet-ajax/understanding-asp-net-ajax-web-services
编辑
我建议您阅读下面 Dave Ward 的博文,其中讨论了安装和配置错误:
http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/
关于c# - Web 服务返回 xml 尽管返回格式是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17569618/