带有一个jquery ajax请求的多个循环

时间:2013-07-15 11:55:42

标签: jquery ajax json

如果可能有2个或更多个循环/每个有一个ajax调用,我正在徘徊?我想要达到的是一个高尔夫记分卡,我在其中获得记分卡的数据和一个json / ajax呼叫中的球员......

以下是我获得记分卡的方法。

scorecard.php:

$scorecard = array();

$result = mysqli_query($con,"SELECT * FROM ga_turndata WHERE fk_turnid = 1 ORDER BY hole_no ASC LIMIT 18");
while($row = mysqli_fetch_array($result)){
    $scorecard[] = array('hole' => $row['hole_no'], 'par' => $row['par'], 'hcp' => $row['hcp']);
}

获取数据的jquery:

$.getJSON('http://mypage.com/json/scorecard.php', function(data) {

        var array = [];

        $.each(data, function (i, val) {

            array.push($("#theholes").append("<li>"+val.hole+"</li>"));

        });
});

这部分就像一个魅力:-)。但是当试图将它添加到scorecard.php时:

$scorecard[] = array('user' => 'Jane Doe', 'id' => '89', 'useraStrokes' => '5');
$scorecard[] = array('user' => 'Jemaine Dice', 'id' => '245', 'useraStrokes' => '17');
$scorecard[] = array('user' => 'Jimmie Gallon', 'id' => '16', 'useraStrokes' => '13');

然后,当然,我得到了3个以上......无论如何,我可以将这些分开,还是应该两次拨打ajax?一个用于记分卡,一个用于球员?

希望得到帮助并提前致谢:-)

3 个答案:

答案 0 :(得分:1)

返回包含两个数组的单个JSON对象:scorecardplayers。然后,在您的AJAX成功回调中,您只需单独迭代它们:

$.getJSON('http://mypage.com/json/scorecard.php', function(data) {
    var array = [];
    $.each(data.scorecard, function (i, val) {
        array.push($("#theholes").append("<li>"+val.hole+"</li>"));
    });

    $.each(data.players, function(i, player) {
        // do something with this player
    });
});

PHP方面看起来像这样:

$scorecard = array();

$result = mysqli_query($con,"SELECT * FROM ga_turndata WHERE fk_turnid = 1 ORDER BY hole_no ASC LIMIT 18");
while($row = mysqli_fetch_array($result)){
    $scorecard[] = array('hole' => $row['hole_no'], 'par' => $row['par'], 'hcp' => $row['hcp']);
}

$players = array();

$players[] = array('user' => 'Jane Doe', 'id' => '89', 'useraStrokes' => '5');
$players[] = array('user' => 'Jemaine Dice', 'id' => '245', 'useraStrokes' => '17');
$players[] = array('user' => 'Jimmie Gallon', 'id' => '16', 'useraStrokes' => '13');

$data = array('scorecard' => $scorecard, 'players' => $players);

// possibly some other stuff?

return json_encode($data);

免责声明:我从未学过PHP,这只是基于从SO上阅读的粗略知识;对上述任何错误道歉。

答案 1 :(得分:0)

最简单的方法,但不是最好的循环两次

 $.getJSON('http://mypage.com/json/scorecard.php', function(data) {

        var array = [];

        $.each(data, function (i, val) {

            array.push($("#theholes").append("<li>"+val.hole+"</li>"));

        });
    $.each(data, function (j, val) {

            array.push($("#scorecard").append("<li>"+val.user+"</li>"));

        });
});

检查是否存在val.user或val.hole的更好方法如果是,则构建li并将其保存在变量中并且仅在循环后添加

答案 2 :(得分:0)

一种方法是使用相应数组中的值返回ajax调用,例如$ data ['scorecards'=&gt; $ scorecards,'users'=&gt; $ users]等。

在jquery中,只需分别从data.scorecards和data.users获取记分卡和用户。

这避免了两次调用ajax。