The first thing that you should consider is the same origin policy restriction. If you are not able to comply with it and your web service is not hosted on the same domain as the consuming AJAX script you may stop reading my answer here and rethink your architecture.
If you are still reading you could start by defining the service contract and implementation as usual:
[ServiceContract]
public interface IFoo
{
[OperationContract]
string GetData(int value);
}
public class FooService : IFoo
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
Then you add a fooservice.svc
file which will expose the service in IIS:
<%@ ServiceHost
Language="C#"
Debug="true"
Service="SomeNs.FooService"
CodeBehind="FooService.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
The last line Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
is extremely important as this is what will allow you to use JSON.
The last part is web.config:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
And finally an HTML page sending AJAX request to consume the service:
<!DOCTYPE html>
<html>
<head>
<title>WCF Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
// Notice the URL here: Need to be hosted on the same domain
url: '/fooservice.svc/getdata',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ value: 7 }),
success: function (result) {
alert(result.d);
}
});
});
</script>
</head>
<body>
</body>
</html>