简体   繁体   中英

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";

这是请求和响应标头

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

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM