【问题标题】:Call JSON wcf service via jQuery通过 jQuery 调用 JSON wcf 服务
【发布时间】:2011-09-02 08:10:50
【问题描述】:

我对使用 jQuery 从 aspx 页面调用 json wcf 方法有疑问。

这是我的测试方法:

    [ServiceContract]
    public interface IEParcelService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "Test")]
        Response<string> Test();
    }

  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class EParcelServiceImpl : IEParcelService
  {    
    public Response<string> Test()
    {
      return WebServiceHelper.Execute(() => "Test Message");
    }    
  }

此服务部署到 IIS。 当我从 Chrome 调用此方法时:http://localhost/TestService/ServiceImpl.svc/Test 一切正常,我可以看到结果。但是当我从 jQuery 调用它时 我有错误:NETWORK_ERR: XMLHttpRequest Exception 101。我尝试在 Google 中找到解决方案。 但结果并不成功。我该如何解决?

jQuery 调用:

<script language="javascript">
  $().ready(function () {
            $("#myButt").click(function () {

                $.ajax({
                    cache: false,
                    async: false,
                    type: "GET",
                    url: "http://localhost/EParselService/EParcelServiceImpl.svc/Test",
                    contentType: "application/json",
                    dataType: "json",
                  success: function (data, textStatus){
                                alert('successCallBack called');
                                alert(data);
                                alert(textStatus);
                         },
                   error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('errorCallBack called');
                            alert('textStatus = ' + textStatus + '/nerrorThrown = ' + errorThrown);
                        } 
                 });
                alert('Done!');
            });
        });
</script>

<input type="button" value="Get values from server" id="myButt" />

【问题讨论】:

  • 可能是跨站问题。您是否在同一个 iis 上托管您的 html?看看这里:jasonkelly.net/2009/05/….
  • 我在 IIS 上托管服务,但我的测试网站在 Visual Studio 开发服务器上运行。
  • 好了,您应该将它们都托管在同一个站点上。如果您想使用 XMLHttpRequest,因为它不允许在其范围之外打开追索权。这是为了防止 XSS 攻击。如果您想使用来自不同站点的资源,则必须使用 jsonp 之类的东西(参见我之前发布的内容)。
  • 是的,你是对的。感谢您的帮助。

标签: jquery asp.net wcf


【解决方案1】:

所以这是同源问题。 (见here

对于 XMLHttpRequest,资源必须与请求它的页面位于完全相同的域中。这是为了防止 XSS(参见here)攻击。如果您想使用来自不同域的资源,则必须使用 jsonp 之类的东西。 (请参阅here)有关如何使用 WCF 执行此操作的好教程。

【讨论】:

  • 您提供的链接已失效。
  • @PsychoDUCK 我修复了链接。我最初提供的博客文章不再可用。但我发现了另一个基本上提供相同信息的网站
猜你喜欢
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
  • 2011-11-21
  • 2010-11-19
  • 1970-01-01
相关资源
最近更新 更多