2012-06-17 63 views
-3

在jQuery中,您可以輕鬆使用他們的Ajax庫。問題是我只需要一次在我的代碼中,所以調用整個JavaScript庫不是必需的。jQuery - Ajax XMLHttpRequest?

我有這段代碼,我一直在努力,但我似乎無法得到它的工作。 我試圖通過點擊一個按鈕來啓動一個PHP腳本。我該怎麼做?

這裏是我多遠我現在:

<div onClick="count();">Click!</div> 
<script> 
    function count() { 
     if (window.XMLHttpRequest) { 
      xhr = new XMLHttpRequest() 
     } else { 
      if (window.ActiveXObject) { 
       var xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
     } 
     xhr.open('GET', 'count.php', false); 
     xhr.onreadystatechange = function() { 
      if (xhr.readyState === 4 && xhr.status === 200) { 
       while (results.hasChildNodes()) { 
        results.removeChild(results.lastChild); 
       } 
       results.appendChild(document.createTextNode(xhr.responseText)); 
      } 
     } 
     xhr.send(); 

    }, false); 
    } 
</script> 

這裏是PHP文件中的代碼:

<?php 
mysql_connect("myhost", "username", "password") or die(mysql_error()); 
mysql_select_db("mydatabase") or die(mysql_error()); 

mysql_query("INSERT INTO `table` (`field`) VALUES(\'+1\'); ") 
or die(mysql_error()); 
?> 
+0

好知道,**你有什麼問題... ** – gdoron

+0

如何打開一個PHP文件用?點擊一個按鈕。這就是我想要做的。 – user1431627

+0

請重讀你的問題,告訴我它在哪裏寫的,或者一個人怎麼理解這個問題。 – gdoron

回答

0
<script> 
function count() { 
    if (window.XMLHttpRequest) { 
     xhr = new XMLHttpRequest() 
    } else { 
     if (window.ActiveXObject) { 
      var xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    } 
    xhr.open('GET', 'count.php', false); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState === 4 && xhr.status === 200) { 
      while (results.hasChildNodes()) { 
       results.removeChild(results.lastChild); 
      } 
      results.appendChild(document.createTextNode(xhr.responseText)); 
     } 
    } 
    xhr.send(); 

}, false); // This Line looks extra. Remove this and try 
} 
</script> 
0

非常短的方法。

HTML

<input type="button" onclick="count()" value="count"> 

JS

function count() { 
    url="yourphp.php"; 
    objX=new XMLHttpRequest(); 
    objX.open("GET",url,false); 
    objX.send(null); 
} 
+0

問題是我不使用jQuery:/ – user1431627

+0

這不是jQuery – vusan

+0

從來不知道JS Vanilla中有一個objX。 – user1431627