h3n
h3n

Reputation: 5248

jquery getJSON callback function not being fired on asp.net mvc jsonresult but works on twitter json api

What seems to be the problem calling the json api from a subdomain?

Asp.net MVC Action


        [AllowAnonymous]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public JsonResult getBalances()
        {
            var balances = new[]
                               {
                                   new {Id = 1, Balance = 3},
                                   new {Id = 2, Balance = 2},
                                   new {Id = 3, Balance = 1}
                               };
            return Json(balances, JsonRequestBehavior.AllowGet);
        }

jquery code


var url = "http://subdomain.mysite.com/getBalances/";

$.getJSON(url + '?callback=?', function (data) {
           alert(data);
        });


But the above script works if I used the twitter api url:


var url = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2";

Here is the request and response headers

The json response is: [{"Id":1,"Balance":3},{"Id":2,"Balance":2},{"Id":3,"Balance":1}]

Upvotes: 1

Views: 1321

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

I suspect that you are violating the same origin policy. The code works with Twitter because Twitter supports JSONP, whereas your controller action simply returns JSON.

If you navigate to http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2&callback=abc you wil notice how the JSON response is wrapped with the callback that you provided as query string parameter:

abc([...])

If you want to achieve the same with your site you should return JSONP. Here's an example of a custom JSONP action result that you could use:

public class JsonpResult : ActionResult
{
    private readonly object _obj;

    public JsonpResult(object obj)
    {
        _obj = obj;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var callbackname = context.HttpContext.Request["callback"];
        var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(jsonp);
    }
}

and your controller action becomes:

[AllowAnonymous]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult getBalances()
{
    var balances = new[]
    {
        new { Id = 1, Balance = 3 },
        new { Id = 2, Balance = 2 },
        new { Id = 3, Balance = 1 }
    };
    return new JsonpResult(balances);
}

and the call:

var url = "http://subdomain.mysite.com/getBalances/";
$.getJSON(url + '?callback=?', function (data) {
    alert(data);
});

Upvotes: 3

Related Questions