跨域Ajax请求(jQuery JSONP MVC)

来源:转载

通过jQuery的$.ajax方法发送JSONP请求

js代码

 1 <script type="text/javascript">

2 function jsonptest2(result) {//jsonptest2必须是全局唯一的方法

3 alert(result.Age + " " + result.Email);//28 [email protected]

4 }

5

6 $.ajax({

7 type: "GET",

8 url: "http://localhost:2528/Default2/JsonAuction/1",//跨域

9 dataType: "jsonp",

10 jsonpCallback: "jsonptest2"

11 });

12 </script>

MVC中C#代码,即请求http://localhost:2528/Default2/JsonAuction/1

 public class Default2Controller : Controller

{

public ActionResult JsonAuction(int id)

{

Person p = new Person() {Age=28,Email="[email protected]" };//模拟数据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;

}

}

 


分享给朋友:
您可能感兴趣的文章:
随机阅读: