jQuery生成多个数组并生成HTML

jQuery generate multiple arrays and generate HTML

本文关键字:HTML 数组 jQuery      更新时间:2023-09-26

我有一个网站,在那里用户可以浏览在画廊格式的产品。此图库将使用ajax调用填充,该调用将类别传递给php脚本,然后php脚本获取与该类别匹配的所有项目,并返回所有项目信息。然后,ajax调用的成功函数需要拆分数据,并将每个项目的数据插入到自己的数组中,该数组将用于生成显示该项目的html。

我正在努力将数据插入到自己的数组部分,因为项目的数量将根据数据库中当前的数量而变化。

到目前为止我写的是:

jQuery函数:
$('.category').click(function() {

    var category;
    if ($(this).hasClass('Shirts')) {
        category = 'shirts';
    }
    if ($(this).hasClass('Hats')) {
        category = 'hats';
    }
    if ($(this).hasClass('Acc')) {
        category = 'acc';
    }
    $.ajax({
        type: 'GET',
        url: 'galleryfetch.php',
        data: { 'category' : category }
    }).done(function(data) {
        alert('Succes ' + data);
        var arr = data.split('#');  // Information split by #
        for (int i = 0; i < (arr.length / 4); i++) { //  arr.length divided by 4 because each item has 4 pieces of information
            // Insert each item into its own array. So the first  array will be arr[0], arr[1], arr[2], arr[3]. Second array will be  arr[4], arr[5], arr[6], arr[7]
        }
    }).fail(function(response) {
        alert('Fail' + response);
    });
});
下面是php脚本:

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $category = $_GET['category'];
    $conn = mysqli_connect('localhost', 'root', 'Changde90', 'database');   
    $rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
    $items = '';
    while ($row = mysqli_fetch_array($rows)) {
        $itemName = $row[1];
        $itemPrice = $row[2];
        $itemImage = $row[3];
        $itemDescription = $row[4];
        $items .= $itemName.'#'.$itemPrice.'#'.$itemImage.'#'.$itemDescription.'#';
    } 
    echo $items;
}

在php中像这样创建数组:

while ($row = mysqli_fetch_array($rows)) {
    $arr[] = $row;
}
echo json_encode(array("data" => $arr));

然后在你的javascript只是解码数据,并使用它在你的代码,因为你喜欢它。例如:

var arr = $.parseJSON(data);
arr.itemName will return the item name
arr.itemprice will return the item price

还记得你在$.each()

里面使用了上面的代码吗?