如何使用Json附加图像 [英] How to Append image using Json

查看:61
本文介绍了如何使用Json附加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个电子商务网站.我遇到了在主页上显示图像的问题.所有相关数据均显示成功.唯一的图像无法显示.检查控制台时没有出现任何错误. 到目前为止我尝试过的东西附在下面.

I am creating an e-commerce site. i ran into the problem of displaying image on home page. all relevant data have displayed success. the only image couldn't be displayed.I didn't get any errors while checking the console. what i tried so far i attached below.

Json **$("#Products").append("<img id='theImg' src='images/' + data[i].image + ' />'");**这是我编写的图像附加代码.

Json **$("#Products").append("<img id='theImg' src='images/' + data[i].image + ' />'");** this is image append code i written.

   function getProducts(){
        $.ajax({
            type: 'GET',
            url: 'all_product.php' ,
            dataType: 'JSON',
            success: function (data) {
                console.log(data);

                for (var i = 0; i < data.length; i++)
                {
                    $("#Products").append("<img id='theImg' src='images/'  + data[i].image  + ' />'");
                    $('#Products').append('<h5>' + data[i].description +  '</h5>');
                    $('#Products').append('<p>' + data[i].price +  '</p>');
                }
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }

all_product.php

<?php
include("db.php");

$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products order by id DESC");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);

if($stmt->execute())
{
    while($stmt->fetch())
    {
        $output[] = array("id"=>$id, "cat_id" =>$cat_id, "brand_id"=> $brand_id,"price"=> $price, "description"=> $description,
            "image"=> $image, "keywords"=> $keywords);
    }
    echo json_encode($output);
}

$stmt->close();
?>

设计

<div class="card" style="width: 18rem;" id="Products">
                    <img id="theImg">
                    <div class="card-body">
                        <h5></h5>
                        <p class="card-text"></p>
                        <a href="#" class="btn btn-primary">Go somewhere</a>
                    </div>
  </div>

推荐答案

您必须按以下方式更改代码.您缺少一个双qoutes,它使stirng变了.

You have to change the code as following. You are missing a a double qoutes which makes variable as stirng.

$("#Products").append("<img id='theImg' src='images/"  + data[i].image  + "' class='your-css-class' />");

这篇关于如何使用Json附加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆