javascript - 将 Javascript 变量发布到 PHP 文档

标签 javascript php jquery html ajax

我想获取标签中 data-id 的值并将其传输到 PHP 变量。

<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>

我已经使用下面的 javascript 获取了 data-id 的值并将其放入变量中,但是它没有发布在页面上。

$(document).on("click", ".view-admin", function () {
 var adminid = $(this).data('id');

 $.post("index.php", {admin_to_pass: adminid});

});

我尝试这样做...

print_r($_POST);

但是显示的数组是空的我在这里做错了什么?这有点新鲜。

最佳答案

如果您尝试在同一页面上发帖(无论如何这都是一个坏主意),您应该在 PHP catch block 上始终有一个 exit/die; 和一个 success 函数$.post 上的回调。

示例:

模拟JS:

<?php $adminid = 1; ?>
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {

    var adminid = $(this).data('id');
    $.post("index.php", {admin_to_pass: adminid}, function(response){
        console.log(response);
    });

});
</script>

在 PHP 上(同一页面):

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo json_encode($_POST['admin_to_pass']);
    exit; // this is important
}

或者

if(isset($_POST['admin_to_pass'])) {
    echo json_encode($_POST['admin_to_pass']);
    exit; // this is important
    // you must have this or you'll catch the whole document
}

由于在您当前的代码中没有,您需要成功回调函数来处理来自服务器的响应:

$.post("index.php", {admin_to_pass: adminid}, function(response){
                                                    ^^^^
    console.log(response); // your response from the server is inside (you can name it any name you want) 
});

关于javascript - 将 Javascript 变量发布到 PHP 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25902737/

相关文章:

javascript - 使用 javascript 去除不允许选择的字符?

javascript - 对象引用的变量重新分配使其他对象保持不变(无 “transitive” 分配)

javascript - 如何随机化(洗牌)JavaScript 数组?

php - ZF2 - 运行时异常 : Module (ZfcUserDoctrineORM) could not be initialized

php - 在php中从多维数组创建嵌套的父子数组

javascript - new Date(1967, 9, 22) 创建指向 10 月 21 日的对象

php - 在不同页面中包含不同样式表的最佳方法是什么?

javascript - 在不知道 div 宽度的情况下水平居中 div,可能吗?

c# - 在应用程序中使用 jquery 访问所有 td 文本的文本

javascript - 想要扩展原型(prototype)方法