Well, in the "tidal" switch from thin clients to fat browsers, it's necessary to use JavaScript to invoke various services in the background.
It is necessary to learn such content by using WCF services for all the products that are maintained by Dick Silk. With the powerful library of jquery, using JavaScript to access WCF services is easy. Colleagues studied a breeze library, so Dick Silk came to experiment with Ajax. Here the implementation of a simple record to mark a moment, later forget to read this diary to cheat.
First, 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 WCF service's profile (note that if there are other projects that start the WCF service should modify the app.config file for the project), add the Servicehostenvironment section to the aspNetCompatibilityEnabled property and set to True:
Copy Code code as follows:
<servicehostingenvironment aspnetcompatibilityenabled= "true" >
<serviceActivations>
<add relativeaddress= "Tablemanager.svc" service= "Tablemanagerintegrationtestservice.testresultservice"
factory= "System.ServiceModel.Activation.WebScriptServiceHostFactory"/>
</serviceActivations>
</serviceHostingEnvironment>
Furthermore, the associated service binding properties are configured to WebHttpBinding so that JS can be invoked:
Copy Code code as follows:
<service name= "Tablemanagerintegrationtestservice.testresultservice" >
<endpoint address= "" binding= "WebHttpBinding" contract= "Tablemanagerintegrationtestservice.itestresultservice" behaviorconfiguration= "Endpbehavior" >
<identity>
<dns value= "localhost"/>
</identity>
</endpoint>
......
II. operational contracts for WCF services
s the service operation contract to invoke must be WebGet or WebInvoke. The WebGet attribute can be called using the HTTP GET method, while the WebInvoke tag allows the HTTP POST method invocation.
I have a simple example where the WCF service receives a date as an argument and returns the log record for that day.
The service contract is defined as follows:
Copy Code code as follows:
[ServiceContract]
public interface Itestresultservice
{
[OperationContract]
[WebInvoke (method = "POST", bodystyle = webmessagebodystyle.wrapped, Responseformat = Webmessageformat.json)]
list<testresultdata> GetData (int year, int month, int date);
}
The markup for the GetData method defines the method to allow HTTP POST method calls, and the returned data is in JSON format. After specifying the return format for the data, we don't need to write any code, and WCF automatically converts a serializable object to its corresponding format.
In the service class, you also need to specify the aspnetcomatibilityrequirements tag, as shown in the following example code:
Copy Code code as follows:
[Aspnetcompatibilityrequirements (requirementsmode=aspnetcompatibilityrequirementsmode.allowed)]
public class Testresultservice:itestresultservice
{
Public list<testresultdata> 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<testresultdata> ();
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;
}
}
}
}
Third, the browser request WCF service
Basically, the $.ajax method requires 8 parameters: type Specifies the action method (such as post), the URL specifies the address of the WCF service, data is passed to WCF (that is, the parameter), the format of the contenttype specified data (such as JSON), and the literal encoding, datatype specifies the format in which data is returned, ProcessData indicates whether data processing is automatically converted into application/x-www-form-urlencoded format, success, and error properties to indicate a callback method after the operation succeeds or fails.
We define the following global variables in our script so that we can call Ajax when we access:
Copy Code code as follows:
var Type, Url, Data, ContentType, DataType, ProcessData;
We write a Callservice method that calls the $.ajax method directly and uses the parameters defined above:
Copy Code code as follows:
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 a call to a service that gets the data entered by the user from the year, month, and date text boxes and invokes the WCF service request data:
Copy Code code 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 succeeds, the callback method specified by the success parameter is invoked, where we can process the returned results.
The return result is a JSON-formatted data, as our example returns a list of results. If you are unsure of its structure, you can add a breakpoint here to see:
You can see the results in the Getdataresult property of the result object. The elements that directly access this attribute will get the result:
Copy Code code 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 my custom two classes for storing the data to be displayed and drawing the table. The code is not written here.
Now, start WCF services, and then run the page we wrote, the result comes out:
The interface is ugly please forgive ^_^. (A little bit of CSS will look much better.) )