【问题标题】:jQuery - Ajax XMLHttpRequest?jQuery - Ajax XMLHttpRequest?
【发布时间】:2012-06-17 07:07:54
【问题描述】:

在 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()); 
?>

【问题讨论】:

  • 很高兴知道,您有什么问题...?
  • 如何通过单击按钮打开 php 文件。这就是我想要做的。
  • 请重新阅读您的问题,告诉我它是在哪里写的,或者一个人如何理解它。
  • “有这段代码我一直在处理,但我似乎无法让它工作。你能找到我的问题吗?”
  • @comfortablejohn。实际上,有了这段代码,找到它并不难,但是,是的,这是一个糟糕的问题。

标签: php javascript mysql


【解决方案1】:
<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>

【讨论】:

    【解决方案2】:

    非常短的方法。

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

    【讨论】:

    • 问题是我不使用jQuery :/
    • 从不知道 JS Vanilla 中有 objX。
    • objX 只是 javascript 变量。我们可以使用任何类似var xmlhttp=new XMLHTTPRequest()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2010-11-14
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多