javascript 跨域调用豆瓣接口 jsonp 的方式
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 标签中

浙公网安备 33010602011771号