jsonp

来源:互联网 发布:excel制作数据录入窗体 编辑:程序博客网 时间:2024/05/23 23:43

说到jsonp对于我这种不入流的人来说 第一个想到的就是json

json

JSON是一种基于文本的数据交换方式,或者叫做数据描述格式.
它就像xml一样。是一种约定的数据格式,

json是一种基于纯文本并且javascript以及后台语言全部支持的轻量级的数据格式。这里用python演示一下。应该很好看懂。

这里写图片描述

假设我们要传递一个arr字典,

>>> arr={}>>> arr['a']=123>>> arr[2]='1991-1-1'>>> d=[6,7,8]>>> arr['d']=d

我们用json封装后,得到了一段txt文本。

{"a": 123, "2": "1991-1-1", "d": [6, 7, 8]}

当客户端接收到这段文本后,用json解封装,就可以获得到原来的数据。

json至此就说这么多。 它和xml的作用相同,不分伯仲。

接下来说说jsonp

jsonp

首先说一个浏览器的同源策略。
浏览器认为自任何站点装载的信赖内容是不安全的。当被浏览器半信半疑的脚本运行在沙箱时,它们应该只被允许访问来自同一站点的资源,而不是那些来自其它站点可能怀有恶意的资源。
那么怎么算同源呢?
同协议,同域名和同端口。
那好,那如果我们在a.com站点上的js需要向b.com的网站请求数据、
可是因为同源策略,直接请求是不能请求到的。所以这里就产生了一个jsonp的方法,不过我们发现,Web页面上调用js文件时则不受是否跨域的影响,其实只要是拥有src这个属性的标签都拥有跨域的能力。

<script> <img> <iframe>

所以呢,我们想实现跨域访问数据的方法就是 把远程server的数据装进js文件里,为客户端提供服务。而json又可以简洁的描述复杂的数据。 多么美妙的方法。所以解决方案就有了。服务器动态生成json数据传递给客户端。光有数据在js的script标签里面是不够的,所以我们可以在请求数据的时候带上一个callback参数给服务端,然后返回时用callback函数包裹json数据,这样传递回来的script脚本就可以使用本地js函数动态执行力了。
另外jQuery ExtJs 等都支持jsonp的框架。

具体例子如下:
首先我们用ajax去请求一下同源的js。
/test/index.html

<!DOCTYPE html><html><head><meta charset="utf-8"><script language="javascript">window.onload=function(){    var xmlhttp=null;    if (window.XMLHttpRequest)    {// code for IE7+, Firefox, Chrome, Opera, Safari      xmlhttp=new XMLHttpRequest();    }    else    {// code for IE6, IE5      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");    }    xmlhttp.onreadystatechange=function()    {      if (xmlhttp.readyState==4 && xmlhttp.status==200)      {        var doc=xmlhttp.responseText;        alert('ajax success! and text is '+doc);      }    }    // xmlhttp.open("GET","http://localhost/test/test.js",true);    xmlhttp.open("GET","http://test.com/test/test.js",true);    xmlhttp.send();}</script></head><body><p> this is localhost/test/index.html </p></body></html>

/test/test.js:

this is test.js !

一开始ajax请求localhost/test/test.js
发现出现alert表明请求成功
这里写图片描述
然后我们将localhost换成test.com 再次请求。发现请求失败无效果。(test.com 指向 127.0.0.1)

那有什么办法呢,jsonp啊 src可以跨域啊

index2.html

<!DOCTYPE html><html><head><meta charset="utf-8"><script src="http://test.com/test/test2.js"></script></head><body><p> this is localhost/test/index2.html </p></body></html>

test2.js

alert('this is test2.js!');

这里写图片描述

测试成功。请求跨域了。

这里是赤裸裸的js。 那么实际中是怎么用呢、

比如这里客户端请求一个id=1 的数据并在请求的时候带上callback,我们返回id=1的数据用json封装到函数里面。

index3.html

<!DOCTYPE html><html><head><meta charset="utf-8"><script>function getAndShow(data){    var info=data;    alert('name:'+info.name+'  age:'+info.age);}</script><script src="http://test.com/test/test3.php?id=1&callback=getAndShow"></script></head><body><p> this is localhost/test/index3.html </p></body></html>

test3.php

<?php/** * @authors:F001 * @blog:   ev1l.cc */$id=@$_GET['id'];$callback=@$_GET['callback'];if($id==1 && isset($callback)){//string json_encode ( mixed $value [, int $options = 0 ] ) //$arr = array (    'name'=>'bob',    'age'=>'18',    );$str='';$str.=$callback.'(';$str.=json_encode($arr);$str.=')';echo $str;}?>

这里写图片描述

这里写图片描述

大体就是这样。
接下来看看 jQuery 对jsonp的支持

jQuery for jsonp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head>     <title>index4</title>      <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>      <script type="text/javascript">    function getAndShow(data)    {    var info=data;    alert('name:'+info.name+'  age:'+info.age);    };     jQuery(document).ready(function(){        // alert('start');        $.ajax({             type: "get",             async: false,             url: "http://test.com/test/test3.php?id=1",             dataType: "jsonp",             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)             jsonpCallback:"getAndShow",             //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据             success: function(){                alert('success!');             },             error: function(){                 alert('error!');             }         });     });     </script>     </head>  <body>    <p> index4.html</p>  </body> </html>

这里写图片描述
至此就差不多了吧。

参考link:http://kb.cnblogs.com/page/139725/

0 0
原创粉丝点击