javascript - 遍历 ajax 调用返回的每一行

标签 javascript json ajax

我有以下代码来对数据库执行查询。它返回一个对象列表,一个对象对应查询的每一行结果:

function getcontent()
{
    var data = {
        "id": "<?php echo $stournid; ?>"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "response.php", 
        data: data,
        success: function(response) {
            //**************************** HERE!!!!
        },
        error: function(jqXHR, textStatus, errorThrown) {
        console.log(JSON.stringify(jqXHR));
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
return false;
}

response.php 文件包含以下内容:

<?php
$id = "";
if (is_ajax()) {
  if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
    $id = $_POST["id"];
    querydata($id);

  }
}

function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function querydata($id){

require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($mysqli->connect_error) {
    die('Errore di connessione (' . $mysqli->connect_errno . ') '
    . $mysqli->connect_error);
}

$myArray = array();

    if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
        while($row = $games->fetch_array(MYSQL_ASSOC)) {
                $myArray[] = $row;
        }
    echo json_encode($myArray);
}
}
?>

这里是返回的数据:

[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]

我想做的是在Javascript中,一一浏览所有返回的行并相应地更新一些div。我在如何迭代返回的行方面遇到困难。

任何帮助表示赞赏。 谢谢

最佳答案

success: function(response) {
    // redponse is an array of objects (so lets loop through it using forEach)
    response.forEach(function(row) {
        // row is a row (object) from the array
        var id = row.id;
        var location = row.location;
        var date = row.date;
        // ... you get the idea
        // do something with the current row (maybe create a div or table row ...)
    });
},

注意: Array.prototype.forEach就像一个循环但更好。检查文档。

不想使用 forEach?

如果您不想使用 forEach,您可以使用旧的 for,如下所示:

success: function(response) {
    // using for is not very pretty, hein?
    for(var i = 0; i < response.length; i++) {
        // response[i] is the i-th row of the array
        var id = response[i].id;
        var location = response[i].location;
        var date = response[i].date;
        // ... you get the idea
        // do something with the current row (maybe create a div or table row ...)
    });
},

关于javascript - 遍历 ajax 调用返回的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42052211/

相关文章:

java - 如何在 Jsp 页面中使用 Ajax 和选择选项标签?

javascript - 如何使用 JavaScript 加载页面而不是重定向?

javascript - 显示 Json 文件中的更多具体项目

angularjs - JSON 树 MongoDB

javascript - Javascript 上的空 .HTML()

javascript - 安全地将 JSON 字符串转换为对象

javascript - 如何通过ajax获取json字符串并转换为php数组?

javascript - 基于对象属性对数组进行排序 - Javascript

javascript - 从选择选项更改获取数据属性的问题

javascript - 如果第一个条件失败,为什么 javascript 会评估多个 AND 条件