PHP jquery multiple getJson 不工作 iam 所做的事


php jquery multiple getJson not working what iam done worng

$.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>');
    }
});

在第一次调用中,我获取board_types ID,在第二次调用中,我使用第一次调用board_types ID获取板类型名称,我想打印VaR Board。

我在你的代码中看到 3 个问题:

  • getJSON 是异步的:在您从服务器获得答案之前执行之后的代码(当 Board 尚未填充时(
  • 板是一个局部变量,在你给getJSON的回调之外不可见
  • i 在执行回调时更改了值(请记住:getJSON 是异步的(

你可以这样做:

$.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>');
    });}
});