一个jsonp的简单实例

 1 <script type="text/javascript">
 2     //添加<script>标签的方法
 3     function addScriptTag(src){
 4         var script = document.createElement('script');
 5         script.setAttribute("type","text/javascript");
 6         script.src = src;
 7         document.body.appendChild(script);
 8     }
 9     
10     window.onload = function(){
11         //搜索apple,将自定义的回调函数名result传入callback参数中
12         addScriptTag("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=apple&callback=result");
13         
14     }
15     //自定义的回调函数result
16     function result(data) {
17         //我们就简单的获取apple搜索结果的第一条记录中url数据
18         alert(data.responseData.results[0].unescapedUrl);
19     }
20 </script>

jquery中使用

 1 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
 2 <script type="text/javascript">
 3    $.ajax({
 4         url:"http://localhost:20002/MyService.ashx?callback=?",   
 5         dataType:"jsonp",
 6         jsonpCallback:"person",
 7         success:function(data){
 8             alert(data.name + " is a a" + data.sex);
 9         }
10    });
11 </script>
1 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
2 <script type="text/javascript">
3     $.getJSON("http://localhost:20002/MyService.ashx?callback=?",function(data){
4         alert(data.name + " is a a" + data.sex);
5     });
6 </script>

 

posted @ 2016-04-06 15:49  北京流浪儿  阅读(373)  评论(0编辑  收藏  举报