您不能使用 JSON 进行跨域 AJAX 调用。您需要使用 JSONP。因此,不要从控制器操作返回常规 JsonResult,而是编写一个自定义操作结果,它将 JSON 包装在作为参数传递的回调中:
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);
}
}
然后让您的控制器操作返回此自定义操作结果:
public ActionResult SomeAction()
{
var result = new[]
{
new { Id = 1, Name = "item 1" },
new { Id = 2, Name = "item 2" },
new { Id = 3, Name = "item 3" },
};
return new JsonpResult(balances);
}
现在您可以跨域使用此操作:
var url = "http://example.com/SomeController/SomeAction/";
$.getJSON(url + '?callback=?', function (data) {
alert(data);
});