duanke2012 2014-02-12 17:47
浏览 27

使用Javascript中的Javascript数据库中的数据

I'd like to show some data of my database with Javascript. Here's my PHP script:

$arrayDatabase =  array();
$statement = $link->prepare("SELECT project.ID, project.titel, project.subtitel, project.plaatje, project.beschrijving, project.link FROM project" );
$statement->execute();
$statement->bind_result($ID, $titel, $subtitel, $plaatje, $beschrijving, $site);
while($statement->fetch()){
    echo '
        <div class="singleProject" id="'.$ID.'">
            <img src="'.$plaatje.'" alt="'.$titel.'" />
            <div>
                <h2>'.$titel.'</h2>
                <div><p>'.$subtitel.'</p></div>
             </div>
        </div>
    ';
    $arrayRij= array($ID, $beschrijving, $site);
    array_push($arrayDatabase, $arrayRij);
}
$statement->close();

But if I use json_encode to get the array to Javascript, it won't work.

var jsArray = <? echo json_encode($arrayDatabase); ?>;

EDIT: In my browser there is only a ';' after var jsArray =

The weird thing is. If a use a multidimensional array on my own like:

$phpArray = array(array("foo", "bar"), array("foo", "bar"));

My script works.

  • 写回答

2条回答 默认 最新

  • drdawt9210 2014-02-12 18:05
    关注

    Although i also think you should go the AJAX way (or do whatever you are trying to do in php and output the final html instead of doing stuff in js), you can fix your current problem this way:

    json_encode returns a string not a javascript object, so you need to parse that in js to get the real object:

    var jsArray = JSON.parse("<? echo json_encode($arrayDatabase); ?>");
    

    note that you may need to use a JSON polyfill for this to work in old ie versions. Also you may need to escape quotes in the string returned from json_encode.

    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料