如何使JS函数每次调用时都从数据库中获取数据


How to make the JS function get the data from the database everytime I call it?

我使用的代码看起来像这样:

<script>
  function getdata() 
  {
  var  employee = 
    <?php 
//connect to database and get employee name
    echo "'" . $row['empnm'] "'";
    ?>;
  }
</script>
<a href="#" onclick="getdata();">print them</a>

它工作,但该函数只在页面加载时运行PHP代码,而不是每次调用该函数时。因此,如果目标员工的姓名被更改,JS函数将显示旧的姓名,直到页面被重新加载。如何使JS函数每次调用时从数据库中获取数据?

查看jQuery等库

然后使用下面的代码

function getdata(){
  $.post("path/to/file.php", function(data) {
        var employee = data;
        // do whatever with the data.
  });
}

,你仍然可以使用相同的html

<a href="#" onclick="getdata();">print them</a>

file.php

<?php
// connect to your db, get your results, echo them back
echo $row['empnm'];
 ?>

当您第一次请求页面时,PHP呈现出一个完整的html字符串,然后浏览器执行生成的html,而不是原始的PHP。比如,你的服务器会发送类似

这样的信息
<script>
  function getdata() 
  {
  var  employee = 
    "hello world";
  }
</script>
<a href="#" onclick="getdata();">print them</a>

因此,就web浏览器所知,"hello world"只是硬编码在那里。

您需要研究AJAX以了解如何使其工作。查看这个初学者使用jQuery的ajax教程:http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/

定义全局变量

<script>
    var employee = <?php echo "'" . $row['empnm'] "'";?>;
    function getdata(){
        return employee;
    }
</script>

现在继续更改变量employee,无论何时更改

<a href="#" onclick="getdata();">print them</a>

如果你在PHP循环中——看起来确实是这样,因为——你可以使用PHP来定义要传递给循环中的getdata()的参数;例如

<script type="text/javascript">
function getdata(employee) {
    // connect to database and get employee name
}
</script>
<?php
foreach ($loopData as $row) {
    print '<a href="#" onclick="getdata(' . $row['empnm'] . ');">print them</a>';
}
?>