-3

在 jQuery 中,您可以轻松地使用他们的 Ajax 库。问题是我的代码中只需要它一次,因此调用整个 JavaScript 库是不必要的。

我有我一直在处理的代码,但我似乎无法让它工作。我正在尝试通过单击按钮来启动 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()); 
?>
4

2 回答 2

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>
于 2012-06-28T06:55:25.130 回答
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);
}
于 2012-12-13T10:02:31.303 回答