I have a web service returning JSON, but now I'd like to modify it to allow callers to specify a callback function so the return goes from: JSON DATA to specifiedFunction(JSON DATA); The way I'm returning JSON right now is just by returning an instance of an object and having .NET do its serialization magic, if I change to just returning a string I can add the name of the function and the brackets around the data but then I end up with quotation marks in the return, because its a string and I don't want those. So how can I go about it?
Reason for this is we want developers calling our API to be able to use the dynamic script tag as explained here http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html
The technique you are after is called JSONP (JSON with Padding).
See How to support JSONP in WCF services:
The
JsonPEncoder
is a wrapping encoder on the WCF JSON encoder. It delegates most calls to the wrapped encoder. TheWriteMesage
methods have been overriden to pad the outgoing message with the callback method. TheJsonBehavior
is used on the service operation to enable JSONP encoding for that operation. The query parameter of the URI that holds the callback function name is specified as theCallBack
property of the behavior.
In WCF 4.0 added support for JSONP. You may use
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
I don't know what version of HTML they're using, but in all the versions that I've used, the src attribute in a script tag has to be a URL. They're somehow using a function instead, and I don't see that working.
Have you actually seen a dynamic script tag work?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With