PHP验证按钮

时间:2017-01-01 16:48:01

标签: php html ajax

我想在我的HTML页面上有一个简单的按钮,如果右键单击一个按钮,每次我的PHP脚本都单击激活。 我尝试使用此代码,暂时没有任何正面结果:

//My html code
<!DOCTYPE html>
<head>
    <title><?php echo $pageTitle; ?></title>
    <meta charset="UTF-16" />
    <link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
    <main>
        <button onclick="doTheFunction();">Run the script</button>
            <script>
            function doTheFunction(){
            xmlhttp = new XMLHttpRequest();
            xmlhttp.open("POST","script.php",true);
            xmlhttp.send();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                  document.getElementById("demo").innerHTML = this.responseText;
                }
              };
            }
            }
            </script>

    </main>
    <footer>
        <?php echo $footer; ?>
    </footer>
</body>

我的PHP代码的一部分:

echo "$result";

1 个答案:

答案 0 :(得分:1)

您的代码对Ajax的结果一无所知。我建议以here作为参考。您最不重要的是:

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };

其中&#34;演示&#34;是要将Ajax结果加载到的元素的Id。否则该结果不会发生任何事情。

修改

让我们清理您的代码,以便脚本和HTML分开:

&#13;
&#13;
function doTheFunction(){
     xmlhttp = new XMLHttpRequest();
     //Set this before sending!!
     xmlhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             document.getElementById("demo").innerHTML = this.responseText;
         }
     };
     }
    //No reason to post
    xmlhttp.open("GET","theme/generator/gensent.php",true);
    xmlhttp.send();
}
&#13;
<head>
    <title><?php echo $pageTitle; ?></title>
    <meta charset="UTF-16" />
    <link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
    <main id="demo">
        <button onclick="doTheFunction();">Run the script</button>
    </main>
    <footer>
        <?php echo $footer; ?>
    </footer>
</body>
&#13;
&#13;
&#13;

我会在关闭正文后将<script>标记放在html的末尾,或者将其包含在另一个文件的标题中。注意 - 我使用GET,因为没有传输敏感信息,脚本应该在HTML之后加载 - 因此放在最后,最后你需要一个带有Id的标签来实际工作。