简体   繁体   中英

jQuery: Is it possible to use a getJSON request inside another getJSON request?

Is it possible to use a getJSON request inside another getJSON request, using jQuery?

Something like this:

// Population the Requests List
// jQuery AJAX call for JSON
$.getJSON( '/workspace/friends/sentRequests', function( data ) {
    // For each item in our JSON, add a table row and cells to the content string
    $.each(data, function(){
        //Loading each user data into global variable.
        $.getJSON( '/workspace/friends/' + this.friendId, function( user ) {
            requestListData.push(user);
        });

        requestTableContent += '<tr>';
        requestTableContent += '<td><a href="#" class="linkshowuser btn btn-info btn-xs"" rel="' + this.friendId + '" title="Show Details">' + this.name + '</td>';
        requestTableContent += '<td><a href="mailto:' + this.email + '">' + this.email + '</a></td>';
        requestTableContent += '<td>' + moment(useListData[-1].activity.date_established).format('MMMM Do YYYY') + '</td>';
        requestTableContent += '<td>' + this.gender + '</td>';
        requestTableContent += '<td><a href="#" class="linkdeleteuser btn btn-danger btn-xs" rel="' + this.email + '">Danger!</a></td>';
    });

    // Inject the whole content string into our existing HTML table
    $('#requestList table tbody').html(requestTableContent);
});

I was wondering if this is possible? And if so what I'm doing wrong here...

EDIT: I'm asking this because it should populate a table with the data from the getJSON requests but it's not.

Yes, it's fine. You're executing the two requests in series here - the second will not be executed until the first returns. This is necessary because the inner request depends on the outer request's response.

If you control the server, you could almost certainly make your application more efficient by returning the combined data from a single request.

In circumstances where the second request doesn't depend on the first, you could make the requests in parallel using jQuery.when , which waits for the completion of several promises

var first = $.getJSON({  ... });
var second = $.getJSON({  ... });


$.when(first, second)
  .done(function(firstResult, secondResult) {
     // Executed when both requests complete successfully
     // Both results are available here 
  })
  .fail(function() {
    // Executed if at least one request fails
  })

jQuery promise documentation

Yes, it is possible. You can execute any JavaScript code inside the callback function of your first request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM