从JSON数据获取图像源

时间:2015-03-03 21:19:50

标签: javascript php ajax json image

我正在尝试调用PHP文件并让它从数据库表('page')返回结果(单个记录的'pageLocation')。然后我想把结果变成一个变量,所以我可以在用html创建图像时使用它。

目前,正在创建图像,但源没有进入,保留了正确大小的默认空图像。

使用Javascript:

        // Loads a list of comics created by the user from the database.

        function loadComic()
        {
        var xmlhttp = new XMLHttpRequest();
        var getID = '<?php echo $_SESSION["userID"]; ?>';
        var url = "loadCom.php?userID="+getID;


        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                loadComicJSON(xmlhttp.responseText);
            }
        }

        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        }

        // JSON parsing for 'loadComic'.

        function loadComicJSON(response)
        {
            var arr = JSON.parse(response);
            var i;
            var out = "";

            document.getElementById("loadList").innerHTML="";

            if (arr.length == 0)
            {
                //Non-relevant code affecting layout if no comics are found.
            }
            else
            {   
                out+="<br>";

                for(i = 0; i < arr.length; i++)
                {

// Gets image source from database.

                    imgSrc = "";
                    tempID = arr[i].comicID;
                    $.post("getCover.php", {'comicID':tempID}, function(result)
                    {
                        imgSrc += ("" + result);
                    }
                    );

                    // Creates image item and associated radio button.

                    out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
                }

            }


        }

    </script>

PHP(getCover.php):

<?php
if (isset($_POST["comicID"]))
{
    include_once('includes/conn.inc.php');
    $checkID = $_POST["comicID"];

    $query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
    $result = mysqli_query($conn, $query);


    $conn->close();
    echo ($result);
}
else
{   
    $checkID = null;
    echo "Error. No comic found.";
}

?>

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

您需要从结果中获取数据,例如:

$row = $result->fetch_assoc()

另外,是的,Jim G是对的,你需要转义那个POST变量。