使用json显示图像

时间:2017-02-12 18:27:15

标签: javascript php jquery html mysql

所有工作从mysql获取图像src ,移动到js文件直到html工作正常但我想知道,为什么(pic)选择器不会在页面上显示我的图像

这是我的php文件,它从与所选标记相关的mysql数据库中获取所有图像。

This is the result shown in browser

    <?php
    $dbhost = '127.0.0.1';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'maalem';


    $sql2 = "SELECT img FROM image WHERE L_ID=:id";
    try {
        $con = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $con->query('SET NAMES utf8');
        $stmt = $con->prepare($sql2);  
        $stmt->bindParam("id", $_GET["L_ID"]);
        $stmt->execute();
        $img = $stmt->fetchAll(PDO::FETCH_OBJ); 
        $con = null;
        echo '{"pics":'. json_encode($img) .'}'; 
        } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    ?>

//this is the javascript file 



    $('#detailsPage').live('pageshow', function (event) {
    var id = getUrlVars()["L_ID"];
    $.getJSON(serviceURL + 'getmarker.php?L_ID=' + id, displayimg);
    });


    function displayimg(data) {
     var imgs = data.pics;
     console.log(imgs);
    $('#pic').append('<img src="' + imgs.img + '"width=160 height=160/>');

    $('#actionList').listview('refresh');

     }


    function getUrlVars() {
    var vars = [],
    hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
     }

//HTML file 

   <!DOCTYPE HTML>
   <html>
    <head>
    </head>

    <body>

        <div id="detailsPage" data-role="page" data-add-back-btn="true">

            <div data-role="header">
                <h1 id="Name"></h1>
            </div>

            <div data-role="content"> 


                <div id="markerDetails">
                    <h2> الوصف </h2>
                    <p id="Dec"></p>
                    <div id="pic"></div>
                </div>



            </div>

        </div>

    </body>

1 个答案:

答案 0 :(得分:0)

问题是<img id="pic"/>您已定义了一个ID为pic的img 在这一行$('#pic').text('<img src="' + imgs.img + '"width=160 height=160/>');中,你试图通过pic获取元素并插入一个不正确的文本。

<div id="pic"></div>这将为您完成工作,在此div中插入img标记usinf innerHTML(javascript)或.html()(jQuery)