使用jQuery-AJAX–读取获得跨域JSONP数据的示例Demo

  •   
  • 4432
  • jQuery
  • 8
  • super_dodo
  • 2015/04/28

在项目开发实践中。例如在想利用ajax去得到一个json接口数据的时候,这时候如果是子啊同一个域名下就不存在跨域情况,使用$.getJSON()即可实现。但是需要跨域的请求其他域名下面的Json数据就需要JSONP的方式去请求。写法和getJSON有差异。直接上Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用jQuery-AJAX--读取获得跨域JSONP数据</title>
    <script src="./jquery-1.7.2.js" type="text/javascript"></script>
    <style type="text/css">
        body,html{font-family: "Microsoft Yahei";}
        a{text-decoration: none;}
    </style>
</head>
<body>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<script type="text/javascript">
$(function() {
    $(".btnAJAX").click(function(){
        $.ajax({
            type : "get",
            async:false,
            dataType : "jsonp",
            jsonp: "callbackparam",             //服务端用于接收callback调用的function名的参数
            jsonpCallback:"weather_callback",   //callback的function名称
            success : function(json){
            //  console.log(json);              //浏览器调试的时候用
                alert(json.weatherinfo.city);
                alert(json.weatherinfo.week);
                alert(json.update_time);
            },
            error:function(){
                alert('fail');
            }
        });
    });
 
});
</script>
 
</body>
</html>

别不好意思拒绝别人,反正那些好意思为难你的人都不是什么好人。