PHP学习9:php如何传数据到js?

这篇博客介绍了如何在PHP中将变量$id传递到JavaScript中,并通过AJAX发送到其他PHP页面处理。作者首先在HTML的button标签中存放$id,然后在JS中通过getAttribute方法获取。此外,还展示了如何直接在JS中使用PHP变量更新页面元素,如用户名、头像和用户信息。
摘要由CSDN通过智能技术生成

一、php传数据给js:

背景:我在Php中有个变量$id,我想要传到js中,在js中通过ajax传到别的php中进行处理。


<div class="q_area">
    <input type="text" name="question" id="myquestion" placeholder="请输入您的问题,小伙伴们将竭尽全力为您解答!">
    <button class="publish" id="surepublish" landid=<?php echo $id;?> >发表</button>
</div>

①于是我把$id 寄放在button标签的属性中

<button class="publish" id="surepublish" landid=<?php echo $id;?> >发表</button>

②在js中取出

<script>
    var surepublish=document.getElementById('surepublish');
    var landid = surepublish.getAttribute('landid');
</script>

 var landid = surepublish.getAttribute('landid');

二、简单方法

<?php
        if(isset($uid)){
            $sql="SELECT * FROM user_form WHERE userid={$uid}";
            $res=mysqli_query($link,$sql);
            $row = mysqli_fetch_assoc($res);      
        }
        ?>

        var touxiang=document.getElementById('touxiang');
        var username=document.getElementById('username');
        var userinfo=document.getElementById('userinfo');
        
        if(isuser){
            username.innerText="<?php echo $row['username']?>";
            touxiang.src="<?php echo $row['portrait']?>";
            userinfo.innerText="<?php echo $row['briefinfo']?>";
        }

username.innerText="<?php echo $row['username']?>";
touxiang.src="<?php echo $row['portrait']?>";
userinfo.innerText="<?php echo $row['briefinfo']?>";

直接在变量后面(等号右边)写php echo.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值