如何使用jQuery AJAX调用的函数WCF服务如何使用、函数、AJAX、jQuery

2023-09-11 22:32:50 作者:转身、泪倾城

我创建简单的WCF服务,并把它添加到ASP.NET MVC应用程序。

I created simple WCF service and added it to ASP.NET MVC application.

该服务有一个方法RepeatString:

The service have a single method RepeatString:

[OperationContract]
public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}

我试图用从后视图(.cshtml)调用此方法并获得方法:

I tried to call this method from a view (.cshtml) using post and get methods:

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');
}

但它们都没有获得成功。

but neither has succeed.

有什么我应该改变WCF服务操作的装修还是我使用jQuery.get /后错?

Is there anything I should change in WCF service operation decoration or am I using jQuery.get/post wrongly?

推荐答案

我会觉得这样的事情...

I would think of something like this...

WCF接口服务

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

那么你的code

Then your code

public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}

未经OperationContract的但页面将从接口派生 所以你的AJAX code会是这样的。

without the operationcontract but the page will be derived from the interface so your ajax code would be something like this.

$.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" );
  });

您可以到$就增加更多的选择。您可以更改完成的承诺,成功,这将做的工作时,操作是成功的。我用的成功,当我在我的WCF服务,需要发送数据至极JSON,并得到它使用JavaScript。 反正你可以阅读更多关于它在这里

you can add more options to the $.ajax. You can change the "done" promise to "success" which will do work when the operation is a success. I used success when i created my wcf services and needed to send data wich json and get it with javascript. anyways you can read more about it on here

写一个JSON字符串或当引号选项variabel

be aware of the single ' and dubble " quote marks when writing a json string or the "option" variabel

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

Now I hope this would help you somehow. Cheers