需求分析
獲取豆瓣電影的api接口的數(shù)據(jù)
接口URL地址: http://api.douban.com/v2/movie/top250?start=6&count=10
解決方案
選擇常見方案JSONP
實現(xiàn)方式一:使用jQuery中的$.getJSON方法獲取數(shù)據(jù)
實現(xiàn)方式二:使用jQuery中的$.Ajax方法獲取數(shù)據(jù)
實現(xiàn)方式三:使用原生JS實現(xiàn)JSONP
方法一:$.getJSON
$.getJSON("https://api.douban.com/v2/movie/top250?callback=?", {
// 上面的callback是指的回調(diào)函數(shù)名的參數(shù)名(一般默認為:callback),供后臺獲取參數(shù)判斷時候使用
// callback后面的問號目尖,是讓系統(tǒng)隨機幫你生成jsonp回調(diào)函數(shù)名普筹,當然你也可以自定義去設置函數(shù)名条获,詳情見方法三。
"start": 6,// 傳到后臺的參數(shù)
"count": 10// 傳到后臺的參數(shù)
}, function (json) {
console.log(json);//輸出JSON格式數(shù)據(jù)
},"json");
方法二:$.Ajax
$.ajax({
type: 'get',
async: true,//默認是異步
url: 'https://api.douban.com/v2/movie/top250?start=6&count=10',
dataType: 'jsonp',
jsonp: 'callback',//回調(diào)函數(shù)名的參數(shù)名(一般默認為:callback)辆憔,供后臺獲取參數(shù)判斷時候用
jsonpCallback: "getMovieListFn",// 這次自定義了回調(diào)函數(shù)的函數(shù)名驯遇,底層掉的時候是掉這個函數(shù)的。
success: function (data) {
console.log(data)
},
error: function (data) {
alert("error");
}
});
方法三:原生JS實現(xiàn)JSONP
// 自定義一個名為handleResponse的函數(shù)掸读,并定義形參response,請求成功后執(zhí)行這個函數(shù)
function handleResponse(response){
console.log(response);// 輸出數(shù)據(jù)
}
var hm = document.createElement("script");
// 給這個動態(tài)創(chuàng)建的script的標簽儿惫,添加src地址
// 并指定callback調(diào)用的函數(shù)為handleResponse澡罚,這樣數(shù)據(jù)請求成功后就會自
// 動去調(diào)用上面的handleResponse函數(shù)
hm.src = "http://api.douban.com/v2/movie/top250?start=6&count=10&callback=handleResponse";
// 獲取頁面中第一個script標簽。
var s = document.getElementsByTagName("script")[0];
// 把動態(tài)創(chuàng)建的這個script標簽放在document中所有script標簽的最前面肾请。
s.parentNode.insertBefore(hm, s);