views:

309

answers:

2

EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE

I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..." Any ideas?

Here is the code:

$.ajax({
    type: "POST",
    url: "http://test/TestService.asmx/HelloWorld?jsonp=?",
    dataType: "jsonp",
    success: function(data) {
        alert(data.prop1);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown);
    }
}); 

And the server code is:

[ScriptService]
public class TestService : System.Web.Services.WebService{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void HelloWorld() {
        string jsoncallback = HttpContext.Current.Request["jsonp"];
        var response = string.Format("{0}({1});", jsoncallback, @"{'prop1' : '" + DateTime.Now.ToString() + "'}");
        HttpContext.Current.Response.Write(response);
    }
}
A: 

Unless you specify the jsonp and/or the jsonpCallback option, jQuery auto-generates the function name for you, and adds a query param like callback=jsonp1272468155143. Which means your application needs to output using that function name.

You can always set jsonpCallback to test, in which case your example would work.

jay_soo
+1  A: 

Hi iboeno!

Glad it's working now.

You're trying to send the parameter, "jsonp" -- that you need to pass for the "padding" part of the json -- as a GET parameter, i.e. in the URL string. Which is the right thing to do.

But because you've specified POST, that's not happening. Effectively, because you're specifying POST, the server is expecting all the parameters to be in the POSTed data, not in GET variables, so it's not checking the URL to retrieve the parameter.

I think it's possible that jQuery is being quite forgiving/smart about how it's doing the JSON evaluation, and therefore still working in IE, because (a) if the server doesn't read the "jsonp" variable, I think it'll send back "({'prop1' : '<today's date>'})", which is still evaluate-able as JSON, and (b) IE doesn't have the same restrictions on cross-site scripting ("same origin" policy) as the other browsers. But I'd need to debug it to be sure.

I'd suggest using FireBug in Firefox to debug what's going on with this sort of request in the future, but the main take-away is that if you're sending parameters as part of the URL, use GET, not POST.

Cheers,

Matt

Matt Gibson
Thanks for the explanation!
iboeno