需掌握的技能點:
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>