2013-07-10 116 views
2

这里是Web服务Web服务返回的XML虽然返回格式是JSON

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 

回答

0

确保在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

编辑

我建议你去通过下面戴夫病房的博客贴子,讨论安装和配置错误:

http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/

0

尝试使用

[ScriptMethod(UseHttpPost=true, ResponseFormat=ResponseFormat.Json)] 

还从您的服务中返回一个对象,以便客户端可以更加可预测地使用它。

return new Result() { Value = "some string" };