我创建了以下 Web 服务,并使用了我需要发布到 Web 服务的最新版本的 jquery。
我想不通。我读过 JSONP 不适用于 POST。我怎样才能让它工作?
我需要使用 jQuery 到 WCF 进行跨域发布。
服务.cs:
namespace AjaxPost
{
[DataContractAttribute]
public class Message
{
[DataMemberAttribute]
public string success;
public Message(string success)
this.success = success;
}
[ServiceContract(Namespace="JsonpAjaxService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class User
{
[WebInvoke(ResponseFormat = WebMessageFormat.Json, Method="POST")]
public Message CreateUser(string email, string username, string password, string phone, string image)
{
Message msg = new Message("true");
return msg;
}
}
}
服务.svc:
<%@ServiceHost
language="c#"
Debug="true"
Service="Microsoft.Samples.Jsonp.CustomerService"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
服务 Web.Config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
</customHeaders>
</httpProtocol>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<serviceDebug includeExceptionDetailInFaults="True" httpHelpPageEnabled="True" />
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
索引.html
wcfServiceUrl = "http://localhost:33695/Service.svc/CreateUser";
$.ajax({
crossDomain: true,
cache: true,
url: wcfServiceUrl,
data: "{}",
type: "POST",
jsonpCallback: "Message",
contentType: "application/json",
dataType: "json",
data: "{ \"myusername\": \"mypassword\" }",
error: function (request, status, error) {
//error loading data
alert("error");
},
success: function (menu) {
alert('success');
}
});