【问题标题】:How to pass data through a hyperlink to a php page using Ajax如何使用 Ajax 通过超链接将数据传递到 php 页面
【发布时间】:2022-01-21 14:21:40
【问题描述】:

我正在尝试使用 Ajax 通过获取请求将数据从超链接传递到页面

最初我可以在没有 Ajax 的情况下直接执行此操作,如下所示

 <a id="link" href="page.php?id=12&pid=12" >pass data</a>

我在 php 中捕捉到下面

<?php $_GET['id'] ?>
<?php $_GET['pid']?>

现在我想使用 Ajax 来执行此操作,因此页面不需要加载

我正在尝试以下

 <a class="choice" id="link" href="page.php?id=12&pid=12" >pass data</a>

$(document).ready(function() {
          
                $(".choice").click(function(e) {
                    e.preventDefault();
                    $.ajax( {
                        <!--insert.php calls the PHP file-->
                        url: "votes.php",
                        method: "get",
                       dataType: 'html',
                        success: function(strMessage) {
                            $("#vote").html(strMessage);
                          
                        }
                    });
                });
            });

但我无法让它工作。我需要有关使用 Ajax 将数据正确实现发送到我的 php 文件的帮助

【问题讨论】:

    标签: php ajax


    【解决方案1】:

    首先,JavaScript 部分需要&lt;script&gt; 标签。 Ajax URL 可以通过$(this).attr('href') 读取&lt;a&gt; 标签href 属性。同样根据您的代码,需要一个带有vote id 的 div,因此添加了&lt;div id="vote"&gt;&lt;/div&gt;

    <a class="choice" id="link" href="page.php?id=12&pid=12" >pass data</a>
    <div id="vote"></div>
    <script>
    $(document).ready(function() {
        $(".choice").click(function(e) {
            e.preventDefault();
            $.ajax( {
                url: $(this).attr('href'),
                method: "get",
               dataType: 'html',
                success: function(strMessage) {
                    $("#vote").html(strMessage);
                  
                }
            });
        });
    });
    </script>
    

    【讨论】:

    • 很棒的实现,是的,有我的脚本标签和
      。缺少的是 Ajax 方法中正确的 url 参数实现。真的很有帮助
    • 谢谢,很高兴。
    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    相关资源
    最近更新 更多