深入浅出JSONP--解决ajax跨域问题

JSONP和JSON好像啊,他们之间有什么联系吗?

  JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。对于JSON大家应该是很了解了吧,不是很清楚的朋友可以去json.org上了解下,简单易懂。

  JSONP是JSON with Padding的略称。它是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。--来源百度

实现代码:

 $("#btnAjax").click(function () {
            $.ajax({
                type: "Get",
                url: "http://localhost:4018/Default1/Create?callback=?",
                cache: false,
                error: function () {
                    alert("程序出错,请联系管理员.");
                },
                dataType: "jsonp",
                jsonp: 'callback',
                success: function (data) {
                    alert(data.name);
                 
                }
            });
        });
 public ActionResult Create()
        {
            //获取回调函数名
            string callback = Request.QueryString["callback"];
            //json数据
            string json = "{"name":"chopper","sex":"man"}";
            return Content(callback + "(" + json + ")");
          
        }

ASP.NET MVC实现常用方式

在MVC3.0中建立JSONP专用ActionResult

public class JsonpResult<T> : ActionResult
    {
        public T Obj { get; set; }
        public string CallbackName { get; set; }

        public JsonpResult(T obj, string callback)
        {
            this.Obj = obj;
            this.CallbackName = callback;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var js = new System.Web.Script.Serialization.JavaScriptSerializer();
            var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")";

            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.Write(jsonp);
        }
    }
public ActionResult Create()
        {
            //获取回调函数名
            string callback = Request.QueryString["callback"];
            //json数据
        //  string json = "{"name":"chopper","sex":"man"}";
           // return Content(callback + "(" + json + ")");
            return new JsonpResult<object>(new { success = true, result = new { a=1 } }, callback);
        }

Jsonp的服务器端的原理其实就是回调一个js函数名(这里是callback参数)将该参数传给服务端,接着再由服务器端执行这个callback js函数,
同时附上该js函数的参数。比如上文的C#代码:
var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")";还有一点我们要注意的就是安全隐患问题:
在使用jsonp由于涉及到跨域,需要考虑到对方站点或者对方系统的安全性问题。应当避免安全隐患,不能滥用jsonp。

原文地址:https://www.cnblogs.com/yxlblogs/p/3564291.html