简体   繁体   English

从 Javascript 调用的 PHP 函数不起作用

[英]PHP function calling from Javascript not working

I am working on a posting system in PHP.我正在使用 PHP 开发一个发布系统。 The posting system goes through a SQL database and then prints out data from the database.发布系统通过一个 SQL 数据库,然后从数据库中打印出数据。 I am trying to use javascript to see if the system has been updated.我正在尝试使用 javascript 来查看系统是否已更新。 Basically, I want to use javascript to check whether any new posts have been added.基本上,我想使用 javascript 来检查是否添加了任何新帖子。 I have some code that goes into the database我有一些进入数据库的代码

function minicheck (){
    $query= "SELECT * FROM posts";
    $result= mysql_query($query);
    return mysql_num_rows($result);
}

The function returns the number of rows in the database every 10 seconds.I use javascript to call this function.该函数每 10 秒返回一次数据库中的行数。我使用 javascript 调用此函数。

<?php
     echo(" <script>
        killPage();
        function killPage () {
      setInterval(function(){
    x++;
    alert(".minicheck().");
    }, 10000);
     }
   </script> ");
?>

THe issue i am facing is that the function returns the exact same value no matter whether or not a row has been added into the sql databse.我面临的问题是,无论是否在 sql 数据库中添加了一行,该函数都返回完全相同的值。 Even if I add a row into the sql database, the value that is returned by this function is the exact same every time.即使我在sql数据库中添加一行,这个函数每次返回的值也是完全一样的。

How can I fix this?我怎样才能解决这个问题?

Thank You,.谢谢你,。

You cannot call PHP functions from JavaScript like that.您不能像那样从 JavaScript 调用 PHP 函数。

What you are doing is calling the function once when building your JavaScript, which is then being sent to the browser.您所做的是在构建 JavaScript 时调用该函数一次,然后将其发送到浏览器。

The browser only ever gets the static value you've put in the string, so naturally it can never update.浏览器只会获取您放入字符串中的静态值,因此它自然永远不会更新。

If you want to call something in PHP from JavaScript, you'll probably want to use XMLHttpRequest (or any of the readily available libraries like jQuery that can help w/AJAX) to query a PHP file that runs the function and returns the value.如果您想从 JavaScript 调用 PHP 中的某些内容,您可能需要使用 XMLHttpRequest(或任何可以帮助使用 AJAX 的现成库,如 jQuery)来查询运行该函数并返回值的 PHP 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM