If you send an ajax request using jQuery and request dataType: "jsonp"
, jQuery will pass the name for the callback function in the request (for example, /returndata?s=hello&callback=jquery123456789
), so returning the constant "jsonCallback" will not work in this case .
In addition, in your question, you have a definition of the operation contract that returns Stream
, and in the operation itself you return string
- there is something wrong there.
What you need to do: you have two options. The first one is to let WCF handle the JSONP add-on for you. You will need to return the data type with the "Status" property and just return it. You also need to enable the CrossDomainScriptAccessEnabled
property in the WebHttpBinding used by your endpoint. Your operation will look something like this:
public class MyType { public string Status { get; set; } } [ServiceContract] public class Service { [WebGet(UriTemplate = "returndata?s={s}")] public MyType ReturnData(string s) { return new MyType { Status = "OK" }; } }
The second option, if you want to create JSONP code yourself, is to take an additional parameter in the URI for the name of the callback function, and then use it when creating the response. You also need to return it as a Stream
so that you do not receive a response as a string (which you probably have now). It will look like this:
[ServiceContract] public class Service { [WebGet(UriTemplate = "ReturnData?s={s}&callback={callbackFunctionName}")] public Stream EchoWithGet(string s, string callbackFunctionName) { string jsCode = callbackFunctionName + "({\"Status\":\"OK\"});"; WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript"; return new MemoryStream(Encoding.UTF8.GetBytes(jsCode)); } }
And this jQuery code can be used to access this service:
function StackOverflow_11090835_Test() { var url = "/StackOverflow_11090835.svc/ReturnData"; var data = { s: "Hello world" }; $.ajax({ type: 'GET', url: url, data: data, dataType: "jsonp", success: function (result) { $("#result").text(result.Status); } }); }