问题描述
从子域调用json api似乎是什么问题?
What seems to be the problem calling the json api from a subdomain?
Asp.net MVC操作
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代码
var url = "http://subdomain.mysite.com/getBalances/";
$.getJSON(url + '?callback=?', function (data) {
alert(data);
});
但是如果我使用twitter api url,以上脚本将起作用:
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";
json响应为:[{"Id":1,"Balance":3},{"Id":2,"Balance":2},{"Id":3,"Balance":1}]
The json response is:[{"Id":1,"Balance":3},{"Id":2,"Balance":2},{"Id":3,"Balance":1}]
推荐答案
我怀疑您违反了相同来源政策.该代码可与Twitter一起使用,因为Twitter支持 JSONP ,而您的控制器操作仅返回JSON.
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.
如果导航到http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2&callback=abc
,您会注意到JSON响应是如何与您作为查询字符串参数提供的callback
包装在一起的:
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([...])
如果要在网站上实现相同目标,则应返回JSONP.这是您可以使用的自定义JSONP操作结果的示例:
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);
}
和通话:
var url = "http://subdomain.mysite.com/getBalances/";
$.getJSON(url + '?callback=?', function (data) {
alert(data);
});
这篇关于jQuery getJSON回调函数未在asp.net mvc jsonresult上触发,但在twitter json api上有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!