2016-09-21 54 views
-1

我學習AJAX, 所以我有這樣的HTML代碼:如何知道AJAX請求是否被執行?

<!DOCTYPE html> 
<html> 
<head> 
    <title> 
    My first chat page 
    </title> 
    <meta charset = "utf-8"> 
    <style> 
    #message-area { 
    position: fixed; 
    bottom: 0; 
    width: 100%; 
    } 
    #send-button { 
    float: right; 
    margin: 20px; 
    color: white; 
    background-color: green; 
    } 
    textarea { 
    float: left; 
    width: 90%; 
    height: 4em; 
    font-family: cursive; 
    fon-size: 20px; 
    resize: none; 
    } 

    </style> 
</head> 
<body> 


    <div id="message-area"> 
     <textarea id="myTextarea" > 
     </textarea> 
     <button type="button" id="send-button"> 
     Send 
     </button> 

    </div> 
</body> 
<script> 
var sendButton = document.getElementById("send-button"); 

function trial(){ 
    var xhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      sendButton.innerHTML = this.responseText; 
     } 
     xhttp.open("GET", "insertmessage.php", true); 
     xhttp.send(); 
    } 
} 

sendButton.addEventListener("click", trial); 

</script> 
</html> 

我有這個簡單的PHP代碼:

<?php 
echo "hello"; 
?> 

我要的是,當我點擊發送按鈕,它建立一個AJAX連接,連接到服務器,服務器發送「Hello」,並更改發送按鈕的內部HTML。我在WAMP www目錄的同一個文件夾中嘗試了它們,但它沒有奏效。

+0

你的'xmlhttp'從哪裏來? –

+0

您可以打開瀏覽器檢查器,然後檢查網絡選項卡以查看請求結果 –

+0

對於初學者,您需要在嘗試之後使用sendButton.addEventListener(「click」,trial)而不使用()。 – mhodges

回答

0

只需將

xhttp.open("GET", "insertmessage.php", true); 
xhttp.send(); 

xmlhttp.onreadystatechange = function(){ 
} 

你的Ajax不是送,因爲這些代碼永遠不會執行,因爲你把它放在你的onreadystatechange事件中(此事件只有當你的Ajax請求是發生發送)

xhttp.open("GET", "insertmessage.php", true); 
xhttp.send(); 

讓你的代碼看起來像這樣

var sendButton = document.getElementById("send-button"); 

function trial(){ 
    var xhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      sendButton.innerHTML = this.responseText; 
     } 
    } 
    xhttp.open("GET", "insertmessage.php", true); 
    xhttp.send(); 

} 

sendButton.addEventListener("click", trial); 
0

當您在您的eventListener分配中進行trial()時,trial已經運行併發出ajax調用。它應該已經更新html而不點擊。您可以在這裏驗證您的代碼:http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get

您的按鈕文本應該更新,否則您的PHP服務器有問題。只需將完整構造的php url放入瀏覽器中即可查看響應。

對於這樣的調試,瀏覽器調試工具非常方便,例如, Chrome有一個網絡標籤,可以告訴你關於你的請求的一切。

+0

當我請求php頁面時,它會打招呼! –

+0

單擊按鈕時,網絡不顯示任何內容。 –

+0

你能解釋第一部分嗎?你的意思是說它不會被點擊,因爲我沒有把它存儲在一個變量中?像var x = function()? –

相關問題