0
$.getJSON("Index/Locations_By_Ratings",function (data) {
    $('#LocationsContainer').html('');
    for (var i = 0; i < data.length; i++)
    {
        $.getJSON('Index/Get_Board_Type',{id:data[i].board_type},function (board_type) {
            var Board = board_type['board_types'];
        });
        $('#LocationsContainer').append('<div class="LocationBox">\
                                            <div class="left">\
                                            <div class="LocationRow"><b>Board Type</b> : '+Board+'</div>\
                                            <div class="LocationRow"><b>Area</b> : '+data[i].location+'</div>\
                                        </div>');
    }
});

in first call iam getting board_types id , in second call iam getting board type name using first call board_types id , and i want to print var Board.

4

1 回答 1

0

I see 3 problems in your code :

  • getJSON is asynchronous : the code just after is executed before you get the answer from the server (when Board isn't yet filled)
  • Board is a local variable, not visible outside the callback you give to getJSON
  • i has changed value when the callback is executed (remember : getJSON is asynchronous)

You can do this :

$.getJSON("Index/Locations_By_Ratings",function (data) {
    $('#LocationsContainer').html('');
    for (var i = 0; i < data.length; i++)
    {
        var theData = data[i];
        $.getJSON('Index/Get_Board_Type', {id:theData.board_type},function (board_type) {
            var Board = board_type['board_types'];
            $('#LocationsContainer').append('<div class="LocationBox">\
                                                <div class="left">\
                                                <div class="LocationRow"><b>Board Type</b> : '+Board+'</div>\
                                                <div class="LocationRow"><b>Area</b> : '+theData.location+'</div>\
                                            </div>');
    });}
});
于 2012-08-26T08:20:48.453 回答