【问题标题】:Send php request onclick via ajax通过ajax发送php请求onclick
【发布时间】:2017-02-06 06:04:07
【问题描述】:

我知道这个问题被问了很多,但没有一个答案与我的案例有关,我有一个按钮,点击它应该调用一个 javascript 函数,向它发送一个 php 变量,ajax 会通过 post 调用一个 php 文件和发送该变量,php 文件会更新我的表

所以这里首先是 onclick 事件

<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>

它应该向 javascript 函数发送一个名为 $id 的变量

<script type="text/javascript">
    function incrementclicks(id) {
        $.ajax({
            url: "increment.php",
            data: "id=" + id,
            type: "POST"
        });
    }
</script>

和 php 文件 increment.php(我 100% 确定它可以很好地连接到服务器)

<?php
     require_once 'dbconnect.php';
     $db_handle = new DBController();
     $id=$_POST["id"];
     $q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
     $result = mysql_query($q);
?>

它不会增加,我不明白我在这里做错了什么

【问题讨论】:

  • 页面网络会发生什么?它显示了什么?我的意思是开发者工具>网络
  • 在您的 increment.php 中回显 $q 并直接在您的 mysql 中运行(从 cmd 或从 phpmyadmin)。还要检查您的 linkclicks 是否为 int?
  • 我不认为我的 php 文件首先被调用,这是这里的问题

标签: javascript php mysql ajax post


【解决方案1】:

如果有人以后有这样的问题,我只想回答这个问题

问题是我忘记在开头添加脚本 src

  <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

添加此代码后,我的代码工作得很好:)

【讨论】:

    【解决方案2】:

    使用这种ajax方法来检查问题。如果发现错误,请在控制台中检查问题

    $.ajax({
                    url: "increment.php",
                    type: "post", //send it through post method
                    data: {
                        id:id
                    },
                    success: function (response) {
                        alert("success");
                    },
                    error: function (xhr) {
                        //Do Something to handle error
                        alert("some error found");
                    }
                });
    

    注意:尝试将 type="button" 添加到您的按钮,以免重新加载

    <button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
    

    【讨论】:

    • 好的,谢谢控制台提示我的问题很愚蠢,我只是在我的脚本之前添加了 和成功了,非常感谢
    【解决方案3】:

    首先你可以在php上调试你的代码

    echo $id;
    exit();
    

    我的问题是你在那里遗漏了一些东西..

    【讨论】:

    • 我认为我的 php 文件没有被调用
    • url: "increment.php",将调用与文件相同的域,因此如果该文件位于 localhost:8989 下且服务器位于 localhost:5050 下,则无法正常工作。尝试把整个网址
    • 它们在同一个域中,increment.php 可以自己正常工作,所以我认为问题在于从 ajax 调用它
    • 您如何使用发布数据自行调用 php 文件?你试过邮递员吗?
    • 我做到了,当它自己增加文件时就好了,我不认为 ajax 正在调用它
    猜你喜欢
    • 2018-06-21
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多