AntonCooper
AntonCooper

Reputation: 73

Handling Multiple JSON Objects

If I have a function like this, i pass in a variable of 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;
}

I'm calling over 100 films details through this function and as you can imagine, it takes forever to load the page by doing it this way. I need to easily access the values in the JSON for each film. For example:

alert(getFilmDetails(12345).description);
alert(getFilmDetails(65432).popularity);
alert(getFilmDetails(12345).tagline);

Is there a better way to do this?

Upvotes: 0

Views: 118

Answers (1)

the system
the system

Reputation: 9336

    // 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);

Upvotes: 1

Related Questions