通过jQuery的$.ajax方法发送JSONP请求
js代码
<script type="text/javascript">
function jsonptest2(result) {//jsonptest2必须是全局唯一的方法
alert(result.Age + " " + result.Email);//28 tom@tom.com
} $.ajax({
type: "GET",
url: "http://localhost:2528/Default2/JsonAuction/1",//跨域
dataType: "jsonp",
jsonpCallback: "jsonptest2"
});
</script>
MVC中C#代码,即请求http://localhost:2528/Default2/JsonAuction/1
public class Default2Controller : Controller
{
public ActionResult JsonAuction(int id)
{
Person p = new Person() {Age=,Email="tom@tom.com" };//模拟数据Person类见下面
return = new JsonpResult() { Data=p};
}
}
//自定义返回类型
public class JsonpResult : JsonResult
{
public string Callback { get; set; }
public JsonpResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
} public override void ExecuteResult(ControllerContext context)
{
var httpContext = context.HttpContext;
var callback = Callback;
if (string.IsNullOrWhiteSpace(callback))
{
callback = httpContext.Request["callback"];
}
httpContext.Response.Write(callback);
httpContext.Response.Write("(");
base.ExecuteResult(context);
httpContext.Response.Write(");"); }
} public class Person
{
public int Age
{
get;
set;
}
public string Email
{
get;
set;
} }