使用jQuery通过GET方法调用ASP.NET Web服务功能

the*_*e_V 6 asp.net ajax service jquery

我正在尝试使用jQuery通过GET方法调用Web服务功能,但遇到了问题.这是一个Web服务代码:

[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService  : System.Web.Services.WebService {
    [WebMethod]
    public string Test2()
    {
        string result = null;

    try
        {
            result = "{'result':'success', 'datetime':'" + DateTime.Now.ToString() + "'";
        }
        catch (Exception ex)
        {
            result = "Something wrong happened";
        }

        return result;
    }

}
Run Code Online (Sandbox Code Playgroud)

这就是我调用函数的方式:

$.ajax({ type: "GET",
         url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
         data: "{}",
         contentType: "application/json",
         dataType: "json",
         error: function (xhr, status, error) {
             alert(xhr.responseText);
         },
         success: function (msg) {
             alert('Call was successful!');
         }
     });
Run Code Online (Sandbox Code Playgroud)

方法被成功调用,但结果字符串被XML标记覆盖,如下所示:

<string>
{'result':'success', 'datetime':'4/26/2010 12:11:18 PM'
</string>
Run Code Online (Sandbox Code Playgroud)

因为这个我得到一个错误(调用错误处理程序).有人知道可以做些什么吗?

Spa*_*ain 8

为HTTP POST/GET请求启用ASP.NET ASMX Web服务

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string Test2()
{
   [...]
}
Run Code Online (Sandbox Code Playgroud)


ntz*_*lis 0

  1. json规则:只能访问同一个域的数据!

  2. 唯一的例外是使用jsonp时(由于 .NET 框架中没有 jsonp 序列化器,因此实现起来相当复杂)。
    如果您使用的是标准 Web 服务(而不是 WCF ),您可以在此处找到如何实现此服务的指南。