Delen via


AJAX Service with JSON and XML Sample

Download sample

This sample demonstrates how to use Windows Communication Foundation (WCF) to create an Asynchronous JavaScript and XML (AJAX) service that returns either JavaScript Object Notation (JSON) or XML data. You can access an AJAX service by using JavaScript code from a Web browser client. This sample builds on the Basic AJAX Service sample.

Note

This sample requires that .NET Framework version 3.5 is installed to build and run. Visual Studio 2008 is required to open the project and solution files.

Unlike the other AJAX samples, this sample does not use ASP.NET AJAX and the ScriptManager control. With some additional configuration, WCF AJAX services can be accessed from any HTML page through JavaScript, and this scenario is shown here. For an example of using WCF with ASP.NET AJAX, see AJAX Samples.

This sample shows how to switch the response type of an operation between JSON and XML. This functionality is available regardless of whether the service is configured to be accessed by ASP.NET AJAX or by an HTML/JavaScript client page.

Note

The setup procedure and build instructions for this sample are located at the end of this topic.

To enable the use of non-ASP.NET clients, the sample uses the following configuration section.

<system.serviceModel>
     <behaviors>
          <endpointBehaviors>
               <behavior name="Microsoft.Ajax.Samples.CalculatorServiceAjaxBehavior">
                    <webHttp/>
               </behavior>
          </endpointBehaviors>
     </behaviors>
     <services>
          <service name="Microsoft.Ajax.Samples.CalculatorService">
               <endpoint address="ajaxEndpoint" behaviorConfiguration="Microsoft.Ajax.Samples.CalculatorServiceAjaxBehavior" binding="webHttpBinding" contract="Microsoft.Ajax.Samples.ICalculator" />
          </service>
     </services>
</system.serviceModel>

Note the use of the <webHttp> behavior instead of the <enableWebScript> behavior. The default data format for the webHttp behavior is XML, while the default data format for the enableWebScript behavior is JSON. For more information about the specifics of the webHttp behavior, see Creating WCF AJAX Services without ASP.NET.

The service in the following sample is a standard WCF service with two operations. Both operations require the Wrapped body style on the WebGetAttribute or WebInvokeAttribute attributes, which is specific to the webHttp behavior and has no bearing on the JSON/XML data format switch.

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
MathResult DoMathXml(double n1, double n2);

The response format for the operation is specified as XML, which is the default setting for the <webHttp> behavior. However, it is good practice explicitly specify the response format.

The other operation uses the WebInvokeAttribute attribute and explicitly specifies JSON instead of XML for the response.

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
MathResult DoMathJson(double n1, double n2);

Note that in both cases the operations return a complex type, MathResult, which is a standard WCF data contract type.

The client Web page XmlAjaxClientPage.htm contains JavaScript code that invokes one of the preceding two operations when the user clicks the Perform calculation (return JSON) or Perform calculation (return XML) buttons on the page. The code to invoke the service constructs a JSON body and sends it using HTTP POST. The request is created manually in JavaScript, unlike the Basic AJAX Service sample and the other samples using ASP.NET AJAX.

// Create HTTP request
var xmlHttp;
// Request instantiation code omitted…
// Result handler code omitted…

// Build the operation URL
var url = "service.svc/ajaxEndpoint/";
url = url + operation;

// Build the body of the JSON message
var body = '{"n1":';
body = body + document.getElementById("num1").value + ',"n2":';
body = body + document.getElementById("num2").value + '}';
  
// Send the HTTP request
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);

When the service responds, the response is displayed without any further processing in a textbox on the page. This is implemented for demonstration purposes to allow you to directly observe the XML and JSON data formats used.

// Create result handler 
xmlHttp.onreadystatechange=function(){
     if(xmlHttp.readyState == 4){
          document.getElementById("result").value = xmlHttp.responseText;
     }
}

To set up, build, and run the sample

  1. Ensure that you have performed the One-Time Set Up Procedure for the Windows Communication Foundation Samples.

  2. Build the solution XmlAjaxService.sln as described in Building the Windows Communication Foundation Samples.

  3. Navigate to https://localhost/ServiceModelSamples/XmlAjaxClientPage.htm (do not open XmlAjaxClientPage.htm in the browser from the project directory).

See Also

Other Resources

AJAX Service Using HTTP POST

© 2007 Microsoft Corporation. All rights reserved.