2017-01-01 53 views
0

我想在我的HTML頁面上有一個簡單的按鈕,如果右鍵單擊它,點擊激活每次我的PHP腳本。 我試着用這個代碼,而無需爲那一刻的任何積極的結果: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"; 
+0

這是有點不清楚你期望什麼?你也沒有對你的ajax調用做任何事情。 – kabanus

回答

1

你的代碼是什麼都不做與阿賈克斯的結果。我建議以here作爲參考。缺失的最重要的東西是:

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

其中「demo」是您要加載Ajax結果的元素的Id。否則,結果將不會發生。

編輯

讓我們來收拾你的代碼,以便腳本和HTML是分開的:

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(); 
 
}
<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>

我會把<script>標籤在你的HTML結束後,關閉主體,或將其包含在另一個文件的標題中。注意 - 由於沒有傳輸敏感信息,所以我使用GET,腳本應該在HTML之後加載,因此最後需要一個帶有Id的標籤才能真正起作用。

+0

謝謝您的回答,並感謝您的建議。不過,我已將您的代碼添加到我的代碼中,但不幸的是沒有任何反應 – frank

+0

發佈您的html,我們將看到如何解決它。你需要一個'div'或者一些其他元素與'id = demo',就像我寫的那樣。我通常使用特殊的ID,比如「ajax」。 – kabanus

+0

完成(y):) – frank