如何在特定的时间跨度使用 AJAX 检索 php 表单


How to retrieve a php form with AJAX at specific time spans

我想显示一个表单,其中包含我根据此问题改编的脚本。该脚本位于我编写的名为 query.js 的文件中,其目的是在位于我项目索引中的div 中打印名为"dbMinAlert.php"的 php 表单的内容<div id="recentExits" name="recentExits"></div>,我尝试使用此标签在我的索引.php文件中调用getNewData(); <body onLoad="getNewData()">但它似乎根本没有做任何事情。

var data_array = '';  // this is a global variable
function getNewData() {
    $.ajax({
        url: "dbMinAlert.php",
    })
    .done(function(res) {
        data_array = res;  // the global variable is updated here and accessible elsewhere
        getNewDataSuccess();
    })
    .fail(function() {
        // handle errors here
    })
    .always(function() {
        // we've completed the call and updated the global variable, so set a timeout to make the call again
        setTimeout(getNewData, 2000);
    });
}
function getNewDataSuccess() {
    //console.log(data_array); 
    document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`

---这个php代码有效,它实际上完成了我期望它做的事情。真正的问题是javascript,就我所关心的那样,下一个php表单可以打印"Hello world"消息,但我希望它显示在我放置在索引中的div中,而不必将内容发布到dbMinAlert.php。

define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site''s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
    SELECT *
    FROM outputs, products
    WHERE products.idProduct=outputs.idProduct
    ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
    $date = date_create($data['Date']);
    $time = date_create($data['Time']);
    echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';

您必须首次执行该函数。

getNewData();

这可能是您从 php 返回结果的方式。与其做多个回显,不如先在单个 php 变量中分配结果,最后做单回显。

$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo  $result;

我在这个问题中找到了一个解决方案,我的代码最终是这样的。我只需要通过键入 <body onload="return getOutput();"> 来调用索引中的函数

JavaScript

        //Min-Max Alerts
    // handles the click event for link 1, sends the query
    function getOutput() {
      getRequest(
          'dbMinAlert.php', // URL for the PHP file
           drawOutput,  // handle successful request
           drawError    // handle error
      );
      return false;
    }  
    // handles drawing an error message
    function drawError() {
        var container = document.getElementById('recentExits');
        container.innerHTML = 'Bummer: there was an error!';
    }
    // handles the response, adds the html
    function drawOutput(responseText) {
        var container = document.getElementById('recentExits');
        container.innerHTML = responseText;
    }
    // helper function for cross-browser request object
    function getRequest(url, success, error) {
        var req = false;
        try{
            // most browsers
            req = new XMLHttpRequest();
        } catch (e){
            // IE
            try{
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                // try an older version
                try{
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    return false;
                }
            }
        }
        if (!req) return false;
        if (typeof success != 'function') success = function () {};
        if (typeof error!= 'function') error = function () {};
        req.onreadystatechange = function(){
            if(req.readyState == 4) {
                return req.status === 200 ? 
                    success(req.responseText) : error(req.status);
            }
        }
        req.open("GET", url, true);
        req.send(null);
        return req;
    }