通过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>(contacts);
        }
    }

前台调用代码


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

    通过查看火狐浏览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")
                };
            }

    前台调用代码

    
    
    

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

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

      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这种方式是可以跨域共享,但是这只是一种

      你可能感兴趣的:(通过jsonp解决浏览器的跨域共享)