繁体   English   中英

jQuery生成多个数组并生成HTML

[英]jQuery generate multiple arrays and generate HTML

我有一个网站,用户可以在其中浏览画廊格式的产品。 该库将使用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()中使用了上面的代码

希望这对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM