如何在同一页面上使用windows.location.href将js值传递给php时停止刷新页面


How to stop refreshing page when passing js value to php using windows.location.href on the same page

在我的页面中,当用户单击<div>时,它会打开一个模态,并在该单击中向该模态传递一个值。现在,由于该值在javascript中,我想将其传递给php,以便可以将其用于查询。我使用的是window.location.href,但当我单击模态时,它会刷新页面,因此不会打开模态。

JS代码:

<script>
        $(document).ready(function(){
          $('#editModal').on('show.bs.modal', function (e) {
            var id = $(e.relatedTarget).data('id');
            //window.location.href = "tasks.php?id="<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>"&final=" + id;              
           jQuery.ajax({
            url:'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',
            type: "POST",
            data: {'name': id},
            dataType: 'text',
            success: function(data)
                {
                   alert(id);
                }
            });

           });
        });
</script>

PHP代码|tasks.PHP?id=2(2只是一个样本值,根据用户在上一页上点击的内容可能会有所不同)

<?php 
        include('config.php');                                                      
        $value = $_POST['name']; //returns unidentified index
        //$value = $_POST['final'];
        echo "I got your value! $value";
?>

每次我尝试打开模态时,它都会不断刷新页面。这样一来,我实际上就无法查看或查看该值是否已传递。有没有更有效的方法在同一页上传递这个信息?或者如何阻止页面刷新?我们将非常感谢你的帮助。非常感谢。

一旦分配了window.location.href,浏览器就会自动转到新的URL。

为了实现您想要的,我建议您改为使用AJAX请求。

由于您使用的是jQuery,他们有一个很棒的助手,可以提供您所需的一切,并从浏览器细节中抽象出来。请参阅此处-http://api.jquery.com/jquery.ajax/.