原生JS和jQuery分别使用jsonp来获取“当前天气信息”

需掌握的技能点:

  jsonp、跨域相关等。

  以下两种代码,均可直接运行。

 

1、使用原生JS:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <p id="cur_year"></p>
    <div id="iciba_ds"></div>
</body>
</html>
<script type="text/javascript">
    document.getElementById("cur_year").innerHTML =new Date();

    function data(data){
        //遍历
        var description = "";
        for(var i in data.result){
            var property=data.result[i];
            description+=i+" = "+property+"<br />";
        }
        document.write(description);
    }
</script>
<script type="text/javascript" src="http://api.k780.com:88/?app=weather.today&weaid=412&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json&jsoncallback=data"></script>

2、使用jquery:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $.ajax({
                type          : 'get',
                async         : false,
                url           : 'http://api.k780.com/?app=weather.today&weaid=412&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json&jsoncallback=data',
                dataType      : 'jsonp',
                jsonp         : 'callback',
                jsonpCallback : 'data',
                success       : function(data){
                    if(data.success!='1'){
                        alert(data.msgid+' '+data.msg);
                        exit;
                    }
                    //遍历
                    var description = "";
                    for(var i in data.result){
                        var property=data.result[i];
                        description+=i+" = "+property+"<br />";
                    }
                    document.write(description);
                },
                error:function(){
                    alert('fail');
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>

 

posted @ 2018-06-24 23:38  我们家的小常客  阅读(1320)  评论(0编辑  收藏  举报