.net MVC下跨域Ajax请求(JSONP)

霸气de小男生 提交于 2020-02-01 02:30:01

一、JSONP(JSON with Padding)

  客户端:

<script type="text/javascript">
    function TestJsonp() {
        $.ajax({
            type: "GET",
            url: "http://localhost/MVC/Books/JsonpTest",
            dataType: "JSONP",
            jsonpCallback: "ExecJsonpCallback"
        })
    }

    function ExecJsonpCallback(obj) {
        alert(obj.Name);
    }
</script>

  服务端:

    public class JsonpResult : JsonResult
    {
        public JsonpResult()
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = context.HttpContext;
            string callback = context.HttpContext.Request["callback"];
            httpContext.Response.Write(callback + "(");
            base.ExecuteResult(context);
            httpContext.Response.Write(");");
        }
    }
    public class BooksController : Controller
    {
        public ActionResult JsonpTest()
        {
            return new JsonpResult { Data = new { Name = "JSONP" } };
        }
    }

  要点:1.Ajax不能直接取得返回,通过回调函数获得结果;

    2.所有的JSONP请求必须是GET请求,MVC默认拒绝AJAX的GET请求,所以需设置JsonRequestBehavior.AllowGet

    3.这是不安全的方式,不要用于敏感信息发送

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!