如何从数据库中获取数据后更改图像

时间:2016-02-26 11:55:35

标签: jquery json ajax

对于function getDataFromDb()我从数据库中获取最新数据,并且我想使用val["id"]来定义更改您将在function GetImage上看到的图像的条件,但这并不成功。你可以举个例子吗?

<script>

function getDataFromDb()
{
    $.ajax({ 
                url: "getData.php" ,
                type: "POST",
                data: ''
            })
            .success(function(result) { 
                var obj = jQuery.parseJSON(result);
                    if(obj != '')
                    {
                          //$("#myTable tbody tr:not(:first-child)").remove();
                          $("#myBody").empty();
                          $.each(obj, function(key, val) {
                                    var tr = "<tr>";
                                    tr = tr + "<td>" + val["id"] + "</td>";
                                    tr = tr + "<td>" + val["first_name"] + "</td>";
                                    tr = tr + "<td>" + val["last_name"] + "</td>";
                                    tr = tr + "<td>" + val["age"] + "</td>";
                                    tr = tr + "<td>" + val["hometown"] + "</td>";
                                    tr = tr + "<td>" + val["job"] + "</td>";
                                    // tr = tr + "<td>" + "<img src='" + GetImage(parseInt(val["id"]))+"'>" + "</td>";
                                    tr = tr + "</tr>";

                                    $('#myTable > tbody:last').append(tr);
                          });
                    }

            });

}

function GetImage(id){
    var image = document.getElementById("myImage");
    if (image.val["id"] < 10){
        return "pic/img1.jpg"
    } else if (image.val["id"] < 20){
        return "pic/img2.jpg"
    } else {
        return "pic/img3.jpg"
    };
}

setInterval(getDataFromDb, 100);   // 1000 = 1 second
</script>

1 个答案:

答案 0 :(得分:1)

取消注释tr循环中注释的each并使用以下函数

function GetImage(id){

    if (id< 10){
        return "pic/img1.jpg"
    } else if (id< 20){
        return "pic/img2.jpg"
    } else {
        return "pic/img3.jpg"
    };
}