通过jsonp解决浏览器的跨域共享

因为浏览器的同源策略,普通ajax访问跨域请求返回的json数据是不会被浏览器接受的。看下面例子可以看出是访问不到的

首先 定义webapi 后台代码

 public class JsopController : ApiController
    {
        public IHttpActionResult GetAlluser()
        {

            User[] contacts = new User[]

           {

               new User{ Name="123", PhoneNo="111", EmailAddress="[email protected]"},

                new User{ Name="456", PhoneNo="222", EmailAddress="[email protected]"},

              new User{ Name="789", PhoneNo="333",EmailAddress="[email protected]"},

           };

            return Json<IEnumerable<User>>(contacts);

        }
    }

前台调用代码

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<ul id="contacts"></ul>
<script type="text/javascript">

    $(function () {

        var url = "http://localhost:16161/api/Jsop/GetAlluser";

        $.getJSON(url, null, function (contacts) {

            $.each(contacts, function (index, contact) {

                var html = "<li><ul>";

                html += "<li>Name: " + contact.Name + "</li>";

                html += "<li>Phone No:" + contact.PhoneNo + "</li>";

                html += "<li>Email Address: " + contact.EmailAddress + "</li>";

                html += "</ul>";

                $("#contacts").append($(html));

            });

        });

    });
</script>

然后运行程序查看是不能够获得数据的。

通过查看火狐浏览firdebug 查看请求头信息,请求是请求到了,只是没有返回数据而已

Accept	application/json, text/javascript, */*; q=0.01
Accept-Encoding	gzip, deflate
Accept-Language	zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Connection	keep-alive
Host	localhost:16161
Referer	http://localhost:18982/TestCors
User-Agent	Mozilla/5.0 (Windows NT 6.1; rv:36.0) Gecko/20100101 Firefox/36.0

下面我就介绍jsonp来跨域获取数据。

首先还是后台代码

 public HttpResponseMessage GetJsonp(string callback)
        {
            User[] contacts = new User[]

           {

               new User{ Name="123", PhoneNo="111", EmailAddress="[email protected]"},

                new User{ Name="456", PhoneNo="222", EmailAddress="[email protected]"},

              new User{ Name="789", PhoneNo="333",EmailAddress="[email protected]"},

           };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string content = string.Format("{0}({1})", callback, serializer.Serialize(contacts));

            return new HttpResponseMessage(HttpStatusCode.OK)

            {

                Content = new StringContent(content, Encoding.UTF8, "text/javascript")

            };
        }

 前台调用代码

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">

    function GetList(contacts) {
        $.each(contacts, function (index, contact) {

            var html = "<li><ul>";

            html += "<li>Name: " + contact.Name + "</li>";

            html += "<li>Phone No:" + contact.PhoneNo + "</li>";

            html += "<li>Email Address: " + contact.EmailAddress + "</li>";

            html += "</ul>";

            $("#contacts").append($(html));

        });
    }
</script>
<ul id="contacts"></ul>
<script type="text/javascript" src="http://localhost:16161/api/Jsop/GetJsonp?callback=GetList"></script>

 通过运行查看数据返回成功了

 查看火狐浏览器查看响应信息如下:

GetList([{"Name":"123","PhoneNo":"111","EmailAddress":"[email protected]"},{"Name":"456","PhoneNo":"222","EmailAddress":"[email protected]"},{"Name":"789","PhoneNo":"333","EmailAddress":"[email protected]"}])

 他返回的不再是纯的json数据了,而是jsonp数据了。通过javascript脚本执行回调方法。不过通过jsonp这种方式是可以跨域共享,但是这只是一种<script>这个标签不受同源策略影响而已,而且这种方式只能通过http-get方式来实现而已。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。