Consuming WCF WebService from jQuery AJAX (with JSON)
/So the guys at work are pretty sold on jQuery now. Everybody who've used it don't want to go back to vanilla JavaScript (just as I predicted).
One of the things always sitting at the back of my mind is to bridge the call from jQuery.ajax to WCF WebServices.
Finally we had a chance to do this, and it turns out this was pretty easy. Special mention to Alvin Shen and Ron Maman who checked this out.
- Create an AJAX-enabled WCF WebService
- This will update your web.config - the only difference is the WCF bindings used - here are the two interesting bits
<service name="SSW.WCF.Services.BookService">
<endpoint address="" behaviorConfiguration="SSW.WCF.Services.BookServiceAspNetAjaxEndPointBehavior"
binding="webHttpBinding" contract="SSW.WCF.Services.BookService" />
</service><behaviors>
<endpointBehaviors>
<behavior name="SSW.WCF.Services.BookServiceAspNetAjaxEndPointBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behavior> - Here's the jQuery AJAX call
$(document).ready(function() {
$.ajax({
type: "POST",
url: http://localhost/<web app name>/BookingService.svc/DoWork,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);}
});
});
Incredibly easy, the hardest part was working what the url was going to be
UPDATE technologies list:
- jQuery
- WCF WebService (AJAX-enabled WCF WebServices are only available in ASP.NET 3.5 - where they added the webHttpBinding, which does JSON serialization)
UPDATE:
Note that ASP.NET does date serialization a bit differently - there is no proper JSON date standard, and the JavaScript date doesn't match the .NET DateTime class with timezone, you may need to do a bit of work to serialize back to a JavaScript date.
Here's a fun service that we use for testing.
// Add more operations here and mark them with [OperationContract]
[OperationContract]
public object[] TestJSON()
{
return new object[] { DateTime.Now, 1, 1.034f, null, "test" };
}