如何使用jQuery ajax函数调用WCF服务

我创建了简单的WCF服务并将其添加到ASP.NET MVC应用程序中。

该服务有一个方法RepeatString:

[OperationContract] public string RepeatString(string s, int times) { string result = ""; for (int i = 0; i < times; ++i) { result += s; } return result; } 

我尝试使用post和get方法从视图(.cshtml)调用此方法:

 function callAjaxService1() { $.post("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12}, function(data) { alert('data from service'); }, 'json'); } function callAjaxService1() { $.get("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12}, function(data) { alert('data from service'); }, 'json'); } 

但都没有成功。

有什么我应该在WCF服务操作装饰中更改或我是否错误地使用jQuery.get / post?

我会想到这样的事……

wcf接口服务

 [OperationContract] [WebGet(UriTemplate = "/repeatstring", ResponseFormat= WebMessageFormat.Json)] string RepeatString(string s, int times); 

那你的代码

 public string RepeatString(string s, int times) { string result = ""; for (int i = 0; i < times; ++i) { result += s; } return result; } 

没有operationcontract但页面将从界面派生,所以你的ajax代码将是这样的。

 $.ajax({ type: "GET", //to get your data from the wcf service url: "AjaxService1.svc/repeatstring", //you might need to add the hostname at the beginning too data: option // or { propertyname1: "John", propertyname2: "Boston" } }) .done(function() { alert( "got data" ); }); 

您可以为$ .ajax添加更多选项。 您可以将“完成”承诺更改为“成功”,这将在操作成功时起作用。 当我创建我的wcf服务并且需要使用json发送数据并使用javascript获取它时,我使用了成功。 无论如何你可以在这里阅读更多相关信息

在写一个json字符串或“option”变量时,要注意单个'和dubble'引号

现在我希望这会以某种方式帮助你。 干杯

要从javascript调用WCF,需要注意三件事。

  1. 该服务必须使用WebInvoke / WebGet进行修饰,以便从javascript访问。

  2. 添加到配置中,以启用对WCF的脚本调用。

  3. webHttpBinding用于使WCF充当REST服务。