MVC 支持ajax跨域
首先要知道ajax跨域是怎么回事,前面已经介绍过,关键在于要访问的页面如何接受并处理跨域请求,原理就是要接受callback(也可以自定义)参数的值,也就是js方法名,然后在把数据拼成json字符串形式 Response即可,但是在mvc里,要想实现刚刚的过程,则需重写JsonResult。
public class JsonpResult : JsonResult { public JsonpResult(object data) { Data = data; JsonRequestBehavior = JsonRequestBehavior.AllowGet; } public override void ExecuteResult(ControllerContext context) { if (context != null) { string funcName = context.HttpContext.Request["callback"].ToString(); context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.Write(string.Format("{0}({1})", funcName, new JavaScriptSerializer().Serialize(Data))); } } }
controller里调用
[HttpGet] public JsonpResult IsOk(string code) { HttpCookie cookie = Request.Cookies["verification"]; if (cookie != null) { VerificationHelper verification = redis.GetClass<VerificationHelper>(cookie.Value); if (verification != null) { //不区分大小写 if (verification.Id.ToLower() == code.ToLower()) { return new JsonpResult(new { isok = true }); } } } return new JsonpResult(new { isok = false }); }
前端调用
$.getJSON("http://localhost:32628/verification/isok?callback=?", { code: value }, function (data) { if (data.Ok) { $("#verification_succ").css("display", "block"); verificationOk = true; } else { $("#verification_error").css("display", "block"); } });
注意:这个getJSON支持跨域,但是要注意 callback=?这个地方,就是服务器端要接受的参数,即可
浙公网安备 33010602011771号