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

在同一页面内将变量从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;
?>

我知道这已被多次回答,但我要找的是在同一页面内传递变量。 我知道PHP是服务器端脚本,而JS是客户端,因此当页面加载时,它将在JS之前加载PHP,因此不可能这样做。 p>

我在寻求什么 是一种替代方法来执行我的JS任务,即获取后的值? 在地址栏中(//localhost/Task/delete.php?ID=1)。 另外还有一种方法可以将变量传递给PHP,因为该值将用于执行SQL查询。 p>

谢谢 p>

   &lt; script language =“javascript”type =“text / javascript”&gt; 
var url = window.location.href; 
var params = url.split('?ID ='); 
var fdf =(params [1  ])
alert(fdf); 
 
&lt; / script&gt; 
 
&lt;?php 
 $ random = $ _GET [“fdf”]; 
 
echo $ random; 
?&gt; 
   code>  pre> 
  div>

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

The question, despite all the JS in it, appears to be asking:

Given a URL like //localhost/Task/delete.php?ID=1, how can I read the value of ID in delete.php?

The answer is:

$_GET['ID']

The relevant section of the manual is here.