[英]Handling Multiple JSON Objects
如果我有這樣的函數,則傳入一個movieid變量。
function getFilmDetails(movieid) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
async: false,
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
filmDetails = result;
}
});
return filmDetails;
}
通過此功能,我正在調用100多個電影細節,您可以想象,通過這種方式加載頁面需要花費很多時間。 我需要輕松地訪問每部電影的JSON中的值。 例如:
alert(getFilmDetails(12345).description);
alert(getFilmDetails(65432).popularity);
alert(getFilmDetails(12345).tagline);
有一個更好的方法嗎?
// receive a callback------------v
function getFilmDetails(movieid, callback) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
// async: false, // YUCK! Commented out
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
callback(result) // invoke your callback
});
return filmDetails;
}
// make a callback
function workWithData(data) {
alert(data.description);
}
// pass the callback
getFilmDetails(12345, workWithData);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.