01-jsonp学习

来源:互联网 发布:生了二胎 才知熊猫血 编辑:程序博客网 时间:2024/05/21 11:20

</pre>1.jsonp作用<p></p><p><span style="font-size:14px; color:#ff0000"><strong><span style="white-space:pre"></span>解决<span style="font-family:Helvetica,Tahoma,Arial,sans-serif; line-height:25.2px">通过ajax的形式去调用其他网站的接口不行的缺陷</span><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; line-height:25.2px">。</span></strong></span></p><p><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2px">例如: </span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2px" /></p><div class="dp-highlighter" id="" style="font-family:Monaco,'DejaVu Sans Mono','Bitstream Vera Sans Mono',Consolas,'Courier New',monospace; width:679px; overflow:auto; margin-left:9px; padding:1px; word-break:break-all; word-wrap:break-word; line-height:25.2px"><div class="bar"><div class="tools" style="padding:3px; margin:0px; font-weight:bold">Js代码  <a target=_blank target="_blank" title="收藏这段代码" style="color:rgb(16,138,198); text-decoration:underline"><img class="star" src="http://lc87624.iteye.com/images/icon_star.png" alt="收藏代码" style="border:0px" /></a></div></div><ol start="1" class="dp-c" style="font-size:1em; line-height:1.4em; margin:0px 0px 1px; padding:2px 0px; border:1px solid rgb(209,215,220); color:rgb(43,145,175)"><li style="font-size:1em; margin:0px 0px 0px 38px; padding:0px 0px 0px 10px; border-left-width:1px; border-left-style:solid; border-left-color:rgb(209,215,220); line-height:18px; background-color:rgb(250,250,250)"><span style="color:black">$.ajax({  </span></li><li style="font-size:1em; margin:0px 0px 0px 38px; padding:0px 0px 0px 10px; border-left-width:1px; border-left-style:solid; border-left-color:rgb(209,215,220); line-height:18px; background-color:rgb(250,250,250)"><span style="color:black">  url: <span class="string" style="color:blue">"http://www.google.com/search?q=jquery"</span>,  </span></li><li style="font-size:1em; margin:0px 0px 0px 38px; padding:0px 0px 0px 10px; border-left-width:1px; border-left-style:solid; border-left-color:rgb(209,215,220); line-height:18px; background-color:rgb(250,250,250)"><span style="color:black">  success: <span class="keyword" style="color:rgb(127,0,85); font-weight:bold">function</span>(json){  </span></li><li style="font-size:1em; margin:0px 0px 0px 38px; padding:0px 0px 0px 10px; border-left-width:1px; border-left-style:solid; border-left-color:rgb(209,215,220); line-height:18px; background-color:rgb(250,250,250)"><span style="color:black">    alert(json.count)  </span></li><li style="font-size:1em; margin:0px 0px 0px 38px; padding:0px 0px 0px 10px; border-left-width:1px; border-left-style:solid; border-left-color:rgb(209,215,220); line-height:18px; background-color:rgb(250,250,250)"><span style="color:black">  }  </span></li><li style="font-size:1em; margin:0px 0px 0px 38px; padding:0px 0px 0px 10px; border-left-width:1px; border-left-style:solid; border-left-color:rgb(209,215,220); line-height:18px; background-color:rgb(250,250,250)"><span style="color:black">});  </span></li></ol></div><p></p><p>2.jsonp原理</p><p>   <strong><span style="color:#ff0000">从别的网站引入js代码是可行的</span></strong>。</p><p>例如:</p><p>本地html引入外部网站的js</p><p><span style="white-space:pre"></span></p><pre code_snippet_id="1644082" snippet_file_name="blog_20160412_2_8390111" name="code" class="javascript"><script type="text/javascript" src="http://www.xukaiqiang.com/remote.js"></script>

remote.js文件中的内容为:alert("I'm a remote file!");

运行index01.html可以看到弹出了 I'm a remote file!

说明js文件可以跨域调用!


3.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>远程js调用本地函数测试</title><!-- 远程js文件内容localHandler({"result":"I'm remote data!"});引入远程的JS文件,会自动调用localHandler方法 --><script type="text/javascript">var localHandler = function(data) {alert('Im local js method,called by remote js ,return data is":"' + data.result);};</script><script type="text/javascript" src="http://www.xukaiqiang.com/remote.js"></script></head><body></body></html>

如上代码,远程js中写了

localHandler({"result":"I'm remote data!"});
引入到本地就会执行localHandler方法。

这样就实现了跨域并获取数据的目的!



所以服务商在提供接口的时候可以这样写:


protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  //获取JSON数据  String jsonData = getDataAsJson(req.getParameter("symbol"));  //<strong><span style="color:#ff0000;">获取回调函数名</span></strong>  String callback = req.getParameter("callback");  //<strong><span style="color:#ff0000;">拼接动态JS代码</span></strong>  String output = callback + "(" + jsonData + ");  resp.setContentType("text/javascript");  PrintWriter out = resp.getWriter();   out.println(output);      // <strong><span style="color:#ff0000;">输出为 jsonpFunc({"symbol" : "IBM", "price" : "91.42"}); </span></strong> }  


假设这个JSONP服务的URL为http://www.google.com/jsonp,回调的函数名为jsonpFunc,那么可以这样发送JSONP请求:


  1. <
    script type="text/javascript"   
  2. src="http://www.google.com/jsonp&company=IBM&callback=jsonpFunc"></script>  

4.使用JQuery的封装进行实现

1.第一种

jQuery.getJSON(  "http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=?",   function(data) {      alert("Symbol: " + data.symbol + ", Price: " + data.price);  }  );  
其中回调函数名”callback”为”?”,即不需要用户指定,而是由jquery生成,互调函数也不需要单独定义,而是以参数的形式紧接在URL之后,URL中还可以附带供数据查询用的其他参数,如上例中的”symbol=IBM” 


2.第二种

$(function() {$.ajax({url : 'http://wx.lrcyz.com/api/article/query.html',data : {id : 1,name : 'qq'},dataType : 'jsonp',jsonpCallback : 'jsonObject', //服务器封装的方法  形如:jsonObject(data,data,data);success : function(data) {console.log("成功")console.log(data)if (data.list) {var l = data.list;for (var i = 0; i < l.length; i++) {var obj = l[i];$('.test').append("<div> " + obj.id + " </div>")}}//$("#id").append("<div> 1 </div>")},error : function(data) {console.log(data)}});});


3.第三种

jQuery(document).ready(function(){        $.ajax({             type: "get",             async: false,             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",             dataType: "jsonp",             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)             jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据             success: function(json){                 alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');             },             error: function(){                 alert('fail');             }         });     });


0 0
原创粉丝点击