2012-06-17 59 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