dongshanni1611 2013-10-16 07:11
浏览 35

如何在JavaScript中使用PHP?

I tried embedding PHP in my JavaScript code to see what happens. Nothing actually happened. Can someone suggest me a way to do this?

<head>
<script>
function myF() {
    n=document.getElementById("name").value
    r=document.getElementById("reason").value
    <?php
        $f = fopen("VisitorLog.txt", "w");
        fwrite($f, "Profile viewed on "+Date()+" by "+n+" Reason= "+r);
        fclose($f);
    ?>
    document.getElementById("name").disabled=true;
    document.getElementById("reason").disabled=true;
    document.getElementById("register").disabled=true;
    document.getElementById("link").style.display="inline";
    alert("You have successfully registered.");
}
</script>
</head>

I'm new to all this stuff and still learning. Please try explaining in simpler terms. :P

  • 写回答

7条回答 默认 最新

  • dousong9729 2013-10-16 07:16
    关注

    First keep in mind that PHP is rendered on the server and Javascript will be interpreted at your client(Web browser). so if you echo something from PHP it will be sent with the html and it won't be executed with the Javascript as you are assuming here.

    To accomplish what you want here you need to make an AJAX call to a PHP script which will update your views log.

    Edit:

    on update.php file

    <?php
    $n = $_POST['n'];
    $r = $_POST['r'];
    $f = fopen("VisitorLog.txt", "w");
    fwrite($f,"Profile viewed on ".date("Y-m-d H:i:s")." by ".$n." Reason= "+$r);
    fclose($f);
    

    And on your javascript (assuming you have jquery loaded)

    <script>
    function myF()
    {
        $.post("update.php",
                    { 
                        n : document.getElementById("name").value, 
                        r : document.getElementById("reason").value
                    },
                    function({
            document.getElementById("name").disabled=true;
            document.getElementById("reason").disabled=true;
            document.getElementById("register").disabled=true;
            document.getElementById("link").style.display="inline";
            alert("You have successfully registered.");
        }));
    }
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理