【问题标题】:jquery .ajax cross domainjquery .ajax 跨域
【发布时间】:2015-10-06 02:40:34
【问题描述】:

我有一个通过 jquery 调用的简单 WCF 服务。当我使用http://localhost/WcfService2/Service1.svc/GetUser 调用服务时,它工作正常。当我使用主机名调用它时,我收到一条错误消息“NetworkError”。我试过使用 jsonp,但这不会返回成功或失败 - 它只是消失在以太中。

我的网络方法是这样的:

  public string[] GetUser(string Id)
    {
        return ("Joe Bloggs, Pete Smith").Split(',');
    }

我的 web.config 是这样的:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="crossdomain" crossDomainScriptAccessEnabled="true"/>
      </webHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>

        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="EndpBehavior">

          <webHttp/>

        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="WcfService2.Service1">
        <endpoint address="http://nwdev2012/WcfService2/Service1.svc" binding="webHttpBinding" contract="WcfService2.IService1" behaviorConfiguration="EndpBehavior" bindingConfiguration="crossdomain"/>
      </service>
    </services>
    <!--<serviceHostingEnvironment >
      <serviceActivations>
        <add factory="System.ServiceModel.Activation.WebServiceHostFactory"
             relativeAddress="./wsccc1/wscccService.svc"
             service="WcfService2.Service1"/>
      </serviceActivations>
    </serviceHostingEnvironment>-->
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customHeaders>
    </httpProtocol>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

我的 jquery 调用是:

function WCFJSON() {
            var userid = 1234;
            Type = "POST";
            Url = "http://localhost/WcfService2/Service1.svc/GetUser";
            Data = '{"value": " + userid + "}';
            ContentType = "application/json; charset=utf-8";
            DataType = "json";
            ProcessData = true;
            CallService();
        }

        function CallService() {
            $.ajax({
                type: Type, //GET or POST or PUT or DELETE verb
                url: Url, // Location of the service
                data: Data, //Data sent to server
                contentType: ContentType, // content type sent to server
                dataType: DataType, //Expected data format from server
                processdata: ProcessData, //True or False
                async: false,
                crossDomain: true,
                success: function (msg) {//On Successfull service call
                    ServiceSucceeded(msg);
                },
                error: ServiceFailed// When Service call fails
            });
        }

        function ServiceSucceeded(result) {
            if (DataType == "json") {
                resultObject = result.GetUserResult;

                for (i = 0; i < resultObject.length; i++) {
                    alert(resultObject[i]);
                }

            }

        }


        function ServiceFailed(result) {
            alert('Service call failed: ' + result.status + '' + result.statusText);
            Type = null;
            varUrl = null;
            Data = null;
            ContentType = null;
            DataType = null;
            ProcessData = null;
        }

我尝试了其他帖子的许多建议,但没有任何效果。我知道一定很简单,所以请任何建议!

【问题讨论】:

    标签: jquery wcf


    【解决方案1】:

    我在这里看到两个问题,第一,变量的范围,第二,你的数据变量被错误地连接,尝试修改你的脚本如下:

    var Type, Url, Data, ContentType, DataType, ProcessData;
    function WCFJSON() {
        var userid = 1234;
        Type = "POST";
        Url = "http://localhost/WcfService2/Service1.svc/GetUser";
        Data = '{"value": ' + userid + '}';
        ContentType = "application/json; charset=utf-8";
        DataType = "json";
        ProcessData = true;
        CallService();
    }
    

    或者通过参数传递:

    function WCFJSON() {
        var userid = 1234,
            Type = "POST",
            Url = "http://localhost/WcfService2/Service1.svc/GetUser",
            Data = '{"value": ' + userid + '}',
            ContentType = "application/json; charset=utf-8",
            DataType = "json",
            ProcessData = true,
        CallService(Type, Url, Data, ContentType, DataType, ProcessData);
    }
    
    function CallService(Type, Url, Data, ContentType, DataType, ProcessData) {
            $.ajax({
                type: Type, //GET or POST or PUT or DELETE verb
                url: Url, // Location of the service
                data: Data, //Data sent to server
                contentType: ContentType, // content type sent to server
                dataType: DataType, //Expected data format from server
                processdata: ProcessData, //True or False
                async: false,
                crossDomain: true,
                success: function (msg) {//On Successfull service call
                    ServiceSucceeded(msg);
                },
                error: ServiceFailed// When Service call fails
            });
        }
    

    【讨论】:

    • 我建议稍微改变这一点,将它们作为参数传递给CallService() 函数,这样它们就不会出现在全局命名空间之外。例如。 CallService(Type, Url, Data, ContentType, DataType, ProcessedData)。当然,您也需要修改 CallService 函数来满足这些要求。
    • 您好 - 感谢您的快速回复。我已经进行了建议的更改,但这并没有解决问题。
    • 我很确定这是一个跨域问题
    猜你喜欢
    • 2011-03-31
    • 2013-06-04
    • 2023-03-30
    • 2011-07-03
    • 2011-12-30
    • 2013-04-04
    • 2011-07-05
    • 2011-11-06
    相关资源
    最近更新 更多