views:

43

answers:

1

I'm trying to get a cross domain call to work using JSONP within JQuery. In IE, the alert method never executed. In FF/Safari/Chrome, it's always null. I looked at Fiddler and the result from the WCF method is as I'm expecting, which is:

method({"Name":"blah1","Data":"blah2"});

Here's my JavaScript:

$.getJSON("http://localhost:5603/MyService/?method=test", null, function (result) {
    alert("in test: " + result);
    $("#spText").html(result);
});

Here's the WCF method:

[OperationContract]
[WebInvoke(UriTemplate = "", Method = "GET", 
    BodyStyle=WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json)]
public Message Blah()
{
    var j = new { Name = "blah1", Data = "blah2" };

    JavaScriptSerializer s = new JavaScriptSerializer();
    string jsonClient = s.Serialize(j);

    return WebOperationContext.Current.CreateTextResponse("method(" + jsonClient + ");",
        "application/json; charset=utf-8", Encoding.UTF8);
}

I feel like I'm really close on this. Can anyone spot anything I'm doing wrong?

+1  A: 

Try changing

http://localhost:5603/MyService/?method=test

to

http://localhost:5603/MyService/?method=test&callback=?

From the documentation:

If the URL includes the string "callback=?" in the URL, the request is treated as JSONP

References: http://api.jquery.com/jQuery.getJSON/

Ken Redler
That was it. Funny how that works. I was planning to add that according to the spec, and had effectively hard coded it in there ("?method=test" in the original) until I could do the dance to pull that key from the URL in the WCF server, then reapply it before sending the response. Turns out not doing it dynamically was the problem all along. Thanks for the help.
Chris Stewart