码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-03-29 20:46:21      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

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

首先 定义webapi 后台代码

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

            User[] contacts = new User[]

           {

               new User{ Name="123", PhoneNo="111", EmailAddress="111@gmail.com"},

                new User{ Name="456", PhoneNo="222", EmailAddress="222@gmail.com"},

              new User{ Name="789", PhoneNo="333",EmailAddress="333@gmail.com"},

           };

            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="111@gmail.com"},

                new User{ Name="456", PhoneNo="222", EmailAddress="222@gmail.com"},

              new User{ Name="789", PhoneNo="333",EmailAddress="333@gmail.com"},

           };
            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":"111@gmail.com"},{"Name":"456","PhoneNo":"222","EmailAddress":"222@gmail.com"},{"Name":"789","PhoneNo":"333","EmailAddress":"333@gmail.com"}])

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

 

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

标签:

原文地址:http://www.cnblogs.com/dzpblogs/p/4376173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!