1 方式一 通過script 標籤的 src屬性 加載數據 ,之後執行一個回掉函數。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>調豆瓣接口</title> <style type="text/css"> #btna{ font-size: 20px; } </style> <script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript"> //回調函數 function showData (result) { var data = JSON.stringify(result); //json對象轉成字符串 $("#txta").val(data); } // 接口 https://api.douban.com/v2/movie/in_theaters $(function(){ $("#btna").click(function(){ $("head").append("<script src='https://api.douban.com/v2/movie/in_theaters?callback=showData'><\/script>"); }) }) </script> </head> <body> <button id="btna">跨域請求數據</button><br/><br/> <textarea id="txta" style="width: 300px;height: 200px;"></textarea> </body> </html>
測試:
方式二 :ajax 請求
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>調豆瓣接口</title> <style type="text/css"> #btna{ font-size: 20px; } </style> <script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript"> // 接口 https://api.douban.com/v2/movie/in_theaters $.ajax({ type: "GET", url:"https://api.douban.com/v2/movie/in_theaters", dataType:"jsonp", success:function(data){ var d = JSON.stringify(data); //json對象轉成字符串 $("#txta").val(d); } }); </script> </head> <body> <button id="btna">跨域請求數據</button><br/><br/> <textarea id="txta" style="width: 300px;height: 200px;"></textarea> </body> </body> </html>
刷新頁面 ,數據加載到 textarea 標籤中