0

如果我有这样的函数,我会传入一个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);

有一个更好的方法吗?

4

1 回答 1

1
    // 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);
于 2013-03-03T17:06:25.947 回答