jquery - 通过jQuery调用JSON wcf服务

标签 jquery asp.net wcf

我有一个问题,根据使用 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" />

最佳答案

所以这是一个同源问题。 (参见here)

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

关于jquery - 通过jQuery调用JSON wcf服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7280774/

相关文章:

jquery - 从 javascript 调用 VB.net 函数

asp.net - 为什么HttpApplication构造函数被多次调用

c# - 服务引用更新 : generating redundant files

c# - 使用http创建WCF服务

javascript - 垂直平移 Google 柱形图

html - jQuery 单击问题,跨度样式看起来像按钮

asp.net 模拟用户进行网络资源访问

c# - WCF aspNetCompatibilityEnabled ="true"引发异常(加载失败)

jquery - jQuery中,如何组合异步调用,包括json和jsonp

javascript - 如何根据输入有条件地隐藏输入表单的某些部分?