gpt4 book ai didi

jquery - 如何使用 jquery Ajax 将数据发布到 WCF 服务?

转载 作者:行者123 更新时间:2023-12-03 23:05:27 26 4
gpt4 key购买 nike

我在使用 JQUERY AJAX 使用 WCF 服务时遇到问题。我知道这是跨域问题,并且已经阅读了很多有关它的解决方案。但没有一个对我有用。以下是所有相关代码。谁能帮帮我吗?

谢谢

 [OperationContract]
[WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[return: MessageParameter(Name = "result")]


public ServiceSearchResponse GetSearchResults(ServiceSearchParams sParams)
{
/// search function
}

JQUERY:

        $.ajax({
type: 'POST',
url: "http://myserviceurl.com/GetSearchResults",
data: p,
contentType: "application/json; charset=utf-8",
dataType: 'json',
crossDomain: true,
success: function (data) {

alert(data);
},
failure: function (response) {
alert('failed');
},
error: function (response) {
alert(JSON.stringify(response));
}
});

网络配置:

  <system.webServer>        
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>

<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultServiceBehavior">
<!--Added DefaultServiceBehavior referenced at service tag above-->
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="myserives.services.AppServicesAspNetAjaxBehavior">

<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="mypackage.services.MyServices">
<endpoint address="" behaviorConfiguration="myserives.services.AppServicesAspNetAjaxBehavior" binding="webHttpBinding"
bindingConfiguration="LargeSizeMessages" contract="myContractName" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="LargeSizeMessages" maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" crossDomainScriptAccessEnabled="true">
<security mode="None" />
</binding>
</webHttpBinding>

</bindings>

</system.serviceModel>

它是这样的: http://screencast.com/t/b7tsqld6

查看错误: http://screencast.com/t/pWQNAlmMYS3

发布数据中没有任何内容。虽然我正在发布数据。

--- 更新

查看我的 Global.asax ..我在这里做错了什么:

 protected void Application_BeginRequest(object sender, EventArgs e)
{

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

EnableCrossDmainAjaxCall();
}

private void EnableCrossDmainAjaxCall()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
"*");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials",
"true");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"1728000");
HttpContext.Current.Response.End();
}
}

最佳答案

这是一段工作代码。

界面

[ServiceContract]
public interface IDataService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
List<RequestData> GetUser(RequestData data);

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "UsersList/{id}",RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
RequestData UsersList(string id);



}

类实现接口(interface)

public class DataService : IDataService
{

public List<RequestData> GetUser(RequestData data)
{
List<RequestData> list = new List<RequestData>();
if (data.Name.ToUpper() == "MAIRAJ")
{
list.Add(new RequestData
{
Name = "Mairaj",
Age = 25,
Address = "Test Address"
});
list.Add(new RequestData
{
Name = "Ahmad",
Age = 25,
Address = "Test Address"
});

}
return list;
}
public RequestData UsersList(string userId)
{
return new RequestData
{
Name = "Mairaj",
Age = 25,
Address = "Test Address"
};
}

}

自定义类

由于我将此类的对象作为参数传递给方法并返回该对象,因此我正在使用它。您可能不需要它。

[DataContract]
public class RequestData
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Address { get; set; }

}

Web.Config

<configuration>
<configSections>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>

<system.serviceModel>
<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="WCFWebApp.DataService">
<endpoint address="" binding="webHttpBinding" contract="WCFWebApp.IDataService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
</configuration>

这就是你如何调用它

var Data = {
Name: "Mairaj",
Age: 20,
Address: "Test Address"
//userId:1
};
$.ajax({
type: "POST",
url: "/DataService.svc/GetUser",
dataType: "JSON",
data: JSON.stringify(Data),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Data is " + data);
},
error: function () {
}
});

您需要更改 web.config 中服务类的名称和 jquery 代码中调用它的 url。

关于jquery - 如何使用 jquery Ajax 将数据发布到 WCF 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31053771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com