Jquery success function not firing using JSONP

Alright. In case anyone needs to know in the future…In hindsight, the solution probably should have been more obvious than it was, but you need to have the web-response write directly to the response stream. Simply returning a string of JSON doesn’t do it, you need to someone construct it and stream it back. The code in my original post will work fine if you do indeed do that.

Example of service code:

public void DoWork()
{
  //it will work without this, but just to be safe
  HttpContext.Current.Response.ContentType = "application/json"; 
  string qs = HttpContext.Current.Request.QueryString["callback"];
  HttpContext.Current.Response.Write(qs + "( [{ \"x\": 10, \"y\": 15}] )");
}

Just for the sake of being explicit, this is the client-side code.

function localDemo(){
  $.getJSON("http://someOtherDomain.com/Service1.svc/DoWork?callback=?",
    function(data){
      $.each(data, function(i,item){            
        alert(item.x);
      });
  });
}

If there is a better way to do this, I am all ears. For everyone else, I know there is some concept of native support in WCF 4.0 for JSONP. Also, you may want to do a little checking for security purposes – though I have not investigated much.

Leave a Comment