1

这是跨域ajax请求:

$.ajax({
            type: "POST",
            dataType: "jsonp",
            contentType: "application/jsonp",
            data: '{"UserName":"newuser","Password":"pwd"}',
            crossDomain: true,
            async: false,
            url: "http://xxx.xx.xx.xx/MyService/SampleService.svc/GetData",
            jsonpCallback: function (jsonData) {
                console.log(jsonData);
                alert('Hi');
            },
            complete: function (request, textStatus) { 
                alert(request.responseText);
                alert(textStatus);
            },
            error: function (request, textStatus, errorThrown) {
                alert(textStatus);
            }
        });

这是我的 WCF REST 服务的方法:

namespace SampleServiceRestAPI
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class SampleService : ISampleService 
{
   ...
   public string GetData(UserData userData)
   {
      string response = "Hi_" + userData.UserName;
      return response;
   }
   ...
}

界面:

    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetData")]
    [OperationContract]
    string GetData(UserData userData);

数据合约:

[DataContract]
public class UserData
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }
}

和部分web.config

<system.web>
   <compilation debug="true" targetFramework="4.0"/>
   <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>    
</system.web>
<system.serviceModel>
<standardEndpoints>
  <webScriptEndpoint>
    <standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
  </webScriptEndpoint>
</standardEndpoints>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" >
  <serviceActivations>
    <add factory="System.ServiceModel.Activation.ServiceHostFactory" relativeAddress="SampleService.svc" service="SampleServiceRestAPI.SampleService"/>
  </serviceActivations>
</serviceHostingEnvironment>
<services>
  <service behaviorConfiguration="ServiceBehaviour" name="SampleServiceRestAPI.SampleService">
    <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
      bindingConfiguration="webWinBinding" contract="SampleServiceRestAPI.ISampleService" />        
  </service>
  <!--<service behaviorConfiguration="metadataBehavior" name="MyService">
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>-->
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true"  />
    </behavior>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <webHttpBinding>
    <binding name="webWinBinding" maxBufferSize="2147483647" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647">

      <readerQuotas maxArrayLength="100000" maxStringContentLength="2147483647" />
    </binding>
  </webHttpBinding>
</bindings>
</system.serviceModel>
  <!--<system.web.extensions>
  <scripting>
  <webServices>
    <jsonSerialization maxJsonLength="2147483644"/>
    <protocols>
      <add name="HttpPost"/>     
      <add name="HttpPostLocalhost"/>   
    </protocols>      
  </webServices>
</scripting>
</system.web.extensions>-->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
<appSettings>
  <add key="ErrorCodeFile" value="~/App_Data/ErrorCode.txt"/>
</appSettings>

我在 Firebug 中遇到的错误:

“网络错误:500 内部服务器错误 - http://173.161.176.229/MyService/SampleService.svc/GetData?callback=undefined& {%22UserName%22:%22newuser%22,%22Password%22:%22pwd%22}&_= 1369120080493"

4

2 回答 2

0

500 错误表示服务器端出现问题。你应该检查那里出了什么问题。您可能必须查看 WCF 部分。Perharps 这有帮助:http: //msdn.microsoft.com/en-us/library/ms732023.aspx

于 2013-05-21T07:30:55.917 回答
0

您通常不能(见下文)将 HTTP POST 发送到与原始域不同的域上的服务。这通常称为同源策略概念,是浏览器安全限制,

阻止访问不同站点上跨页面的大多数方法和属性

JSONP工作是插入一个带有 JSONP 请求 URL 的<script>标签src,这是一个 HTTP GET 请求。您看到的错误是因为浏览器正在尝试获取正在抛出的资源,500 Internal Server Error因为我认为GET该 URL 不受支持。

如果 JavaScript 和 WCF 服务在同一个域中,则不需要使用 JSONP,并且应该能够执行常规$.ajax()POST。

如果 JavaScript 和 WCF 服务(页面所在的页面)不在同一个域中,则允许跨域请求的一种方法是在您的服务器上启用CORS 。此外,浏览器也必须支持它

于 2013-05-21T07:50:56.520 回答