一、使用jsonp请求
1 $.ajax({ 2 type: "GET", 3 url: "http://10.174.1.1/Home/Test?callback=?", 4 data: { id: "1" }, 5 dataType: "jsonp", 6 jsonp: "callback", 7 success: function (data) { 8 alert(data); 9 }, 10 error: function (XMLHttpRequest, textStatus, errorThrown) { 11 alert(errorThrown); 12 } 13 });
1 //Jsonp跨域访问 2 [HttpGet] 3 public ActionResult Test() 4 { 5 string vid = Request.QueryString["id"]; 6 string callback = Request["callback"]; 7 return new JsonpResult<object>(Member.FirstOrDefault(u => u.id == id).Name, callback); 8 } 9 10 11 public class JsonpResult<T> : ActionResult 12 { 13 public T Obj { get; set; } 14 public string CallbackName { get; set; } 15 16 public JsonpResult(T obj, string callback) 17 { 18 this.Obj = obj; 19 this.CallbackName = callback; 20 } 21 22 public override void ExecuteResult(ControllerContext context) 23 { 24 var js = new System.Web.Script.Serialization.JavaScriptSerializer(); 25 var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")"; 26 27 context.HttpContext.Response.ContentType = "application/json"; 28 context.HttpContext.Response.Write(jsonp); 29 } 30 }
二、跨域资源共享
相比 JSONP 请求,跨域资源共享要简单许多,也是实现跨域 AJAX 请求的首选。不过在 IE9 还没有对该技术的支持,FireFox 就已经支持了
1 $.ajax({ 2 type: "GET", 3 url: "http://10.174.1.1/Home/Test2", 4 data: { id: "1" }, 5 dataType: "json", 6 success: function (data) { 7 alert(data); 8 }, 9 error: function (XMLHttpRequest, textStatus, errorThrown) { 10 alert(errorThrown); 11 } 12 });
1 //跨站资源共享实现跨站AJAX请求 2 public ActionResult Test2() 3 { 4 string vid = Request.QueryString["id"]; 5 HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*"); 6 return Json(Member.FirstOrDefault(u => u.id == id).Name, JsonRequestBehavior.AllowGet);7 8 }
时间: 2024-11-05 12:31:06