Home  >  Article  >  Web Front-end  >  jQuery ajax calls WCF service instance_jquery

jQuery ajax calls WCF service instance_jquery

WBOY
WBOYOriginal
2016-05-16 16:41:571383browse

Well, under the "trend" of converting from thin client to fat browser, JavaScript must be used to call various background services.

The product communications maintained by Diaosi all use WCF services, so it is necessary to learn such content. Using jQuery's powerful library, it is very easy to access WCF services using JavaScript. A colleague studied a breeze library, so I came to try ajax. The implementation is simply recorded here so that you can mark it. If you forget it later, just read this log to cheat.

1. Change the configuration of the WCF service

By default, WCF services are not allowed to be accessed using HTTP requests. We need to modify the configuration file of the WCF service (note that if there are other projects that start the WCF service, the app.config file of the project should be modified), add the aspNetCompatibilityEnabled attribute to the serviceHostEnvironment section and set it to true:

Copy code The code is as follows:



factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>


Moreover, the related service binding attribute must be configured as webHttpBinding so that js can be called:

Copy code The code is as follows:


         
                                                                                                                                                                                                                                                                                                                                
                                                                                                        

......


2. Operation contract of WCF service

The service operation contract to be called must be WebGet or WebInvoke. Properties marked as WebGet can be called using the HTTP GET method, while the WebInvoke mark allows HTTP POST method calls.

I have a simple example here. The WCF service receives the year, month and day as parameters and returns the log records of that day.

The Service Contract of this service is defined as follows:


[ServiceContract]
public interface ITestResultService
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
List GetData(int year, int month, int date);

}


The tag of the GetData method defines that this method allows HTTP POST method calls, and the returned data is in JSON format. After specifying the return format of the data, we do not need to write any code, WCF will automatically convert a serializable object into the corresponding format.

In the service class, you also need to specify the AspNetComatibilityRequirements tag, as shown in the following sample code:


Copy code The code is as follows:

    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class TestResultService : ITestResultService
    {

        public List GetData(int year, int month, int date)
        {
            try
            {
                DateTime start_time = new DateTime(year, month, date, 0, 0, 0);
                DateTime end_time = new DateTime(year, month, date, 23, 59, 59);

                DataSet ds = LogDataAccess.SelectDailyBuildLog(start_time, end_time);

                var test_result_list = new List();

                foreach (DataRow result in ds.Tables[0].Rows)
                {
                    TestResultData result_data = new TestResultData
                    {
                        DeployDate = Convert.ToDateTime(result["StatTime"]).ToString(),
                        ServerName = result["ComponentName"].ToString(),
                        Build = result["Build"].ToString(),
                        Result = result["Result"].ToString(),
                        ServerInformation = result["Versions"].ToString()
                    };

                    test_result_list.Add(result_data);
                }

                return test_result_list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}

三、浏览器请求WCF服务

基本上,$.ajax方法需要8个参数:type指定操作方法(如POST)、url指定WCF服务的地址、data是传给WCF的数据(也就是参数)、contentType指定data的格式(如json)和文字编码、dataType指定返回数据的格式、processData指示是否自动将数据处理成application/x-www-form-urlencoded格式、success和error属性指示操作成功或失败后的回调方法。

我们在脚本中定义如下全局变量,以便调用ajax时访问:

复制代码 代码如下:

var Type, Url, Data, ContentType, DataType, ProcessData;

我们编写一个CallService方法,该方法直接调用$.ajax方法,并使用上面定义的参数:

复制代码 代码如下:

function CallService() {
$.ajax({
        type: Type,
​ ​ url: Url,
Data: Data,
contentType: ContentType,
DataType: DataType,
ProcessData: ProcessData,
Success: function (msg) {
ServiceSucceded(msg);
},
       error: ServiceFailed
});
}

The following is an example of calling a service. This method gets the data entered by the user from the Year, Month and Date text boxes and calls the WCF service to request the data:

Copy code The code is as follows:

function WcfJson() {
Type = "POST";
Url = "http://localhost:8734/TableManagerIntegrationTestService/TestResultService/GetData";
Data = '{"year":' $("#Year").val() ', "month":' $("#Month").val() ', "date":' $("#Date ").val() '}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; varProcessData = true;

CallService();
}

After the data request is successful, the callback method specified by the success parameter will be called, where we can process the return result.

The returned result is data in json format. For example, in our example, a result list is returned. If you are not sure about its structure, you can add a breakpoint here to take a look:
You can see that the result is in the GetDataResult property of the result object. Directly access each element of this attribute to get the result:

Copy code The code is as follows:

function ServiceSucceded(result) {
If (DataType == "json") {
          mainView.clearItem();

for (var i = 0; i < result.GetDataResult.length; i ) {
               var resultObject = result.GetDataResult[i];

resultCollection.add(resultObject.ServerName, resultObject.DeployDate, resultObject.Build, resultObject.Result, resultObject.ServerInformation);
}

mainView.render(document.getElementById("logContainer"));
}
}

resultCollection and mainView are two classes I customized to store data to be displayed and draw tables. The code will not be written here.

Now, start the WCF service, and then run the page we wrote, the result will come out:
Sorry for the ugly interface ^_^. (It will look much better if you adjust the CSS a little bit...)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn