dongying7847 2014-05-08 12:38
浏览 45
已采纳

在同一页面内将变量从JS传递给PHP [关闭]

I know this has been answered many times but what i am looking for is the passing of variables within the same page. I understand that PHP is a server side script while JS is the client side thus when the page loads, it will load PHP before JS thus it is impossible to do so.

What i am seeking is an alternative method to perform my JS task which is to take the value after the ? in the address bar (//localhost/Task/delete.php?ID=1). Else alternatively is there a way around passing the variable into PHP as the value will be used to execute a SQL query.

Thanks

<script language="javascript" type="text/javascript" >
var url = window.location.href;
var params = url.split('?ID=');
var fdf = (params[1])
alert(fdf);

</script>

<?php
$random = $_GET["fdf"];

echo $random;
?>
  • 写回答

2条回答 默认 最新

  • dongzhan5246 2014-05-08 12:45
    关注

    HTML Code

    <div id="content"></div>
    

    Javascript Code

    $(document).ready(function(){
    var url = window.location.href;
    var params = url.split('?ID=');
    var id = (params[1]);
            $.ajax({
            type:"POST",
            url:"page.php",
            data:{id:id},
            success:function(result){
            $("#content").html(result);
            }
            });
       });
    

    PHP Code: page.php

    <?php
    $random = $_POST["id"];
    echo $random;
    ?>
    

    Complete One page code: demo.php

    Note: URL for this page must be demo.php?ID=someValue

    <!DOCTYPE html>
    <html>
    <head>
    <title>Demo</title>
    <script src="js/jquery.js"></script>
    <script>
    $(document).ready(function(){
    var url = window.location.href;
    var params = url.split('?ID=');
    var id = (params[1]);
         $("#submit").click(function(){ $.ajax({
            type:"POST",
            url:"demo.php",
            data:{id:id},
            success:function(result){
            $("#content").html(result);
            $("#submit").hide();
            }
            });
            });
       });
       </script>
    </head>
    <body>
    <button id="submit">Click Me</button>
    <div id="content"></div>
    
    </body>
    </html>
    <?php
    $random = $_POST["id"];
    echo $random;
    ?>
    

    Note: Don't forget to include jquery library file

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样