如何在javascript中传递一个值并在另一个页面上获取它?

时间:2017-02-28 09:36:00

标签: javascript php jquery

的JavaScript

function resultfunction() {
    var result = document.getElementById("result");
    window.location.href = "deleteresult.php?did="+result;
}

PHP

<select id="result">
<?php
   include 'model.php';
   $rs=new database();
   $res=$rs->result();
   while($row=mysql_fetch_array($res)){
        $did=$row["id"];
        $dterm=$row["term"];
?>          
<option id="<?php echo $dterm;?>"><?php echo $dterm;?></option>
<?php } ?>
</select>
<a href="#" onclick="resultfunction()" class="btn dropdown-toggle">Delete </a>

这是我的代码点击删除我希望javascript获取所选选项的id并将其带到下一页....以及如何在下一页上获取它...我想将它用作php变量在下一页????

3 个答案:

答案 0 :(得分:1)

使用此:

&#13;
&#13;
<select id="result">
    <option id="option1">option 1</option>
    <option id="option2">option 2</option>
    <option id="option3">option 3</option>
</select>
<a href="#" onclick=" resultfunction()" class="btn dropdown-toggle">Delete </a> 
<script>
  function resultfunction() { 
    var select = document.getElementById("result"); //<---get the select 
    var result= select.options[select.selectedIndex].value; // <--selectedIndex will let you get the value.
    //window.location.href="deleteresult.php?did=" +result; 
    console.log(result);
  }
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

首先,您需要在option上设置一个值,如:

<option id="option1" value='1'>option 1</option>

我已经为您制作了jQuery演示版,请参阅下面的代码段:

&#13;
&#13;
$('.btn').on('click', function(){
  var result = $("#result").val();
  console.log(result);
  //I've commented this line just for demonstrating purpose
  //window.location.href = "deleteresult.php?did=" + result;
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="result">
    <option id="option1" value='1'>option 1</option>
    <option id="option2" value='2'>option 2</option>
    <option id="option3" value='3'>option 3</option>
</select>
<a href="#" class="btn dropdown-toggle">Delete </a>
&#13;
&#13;
&#13;

Javascript替代方法是使用addEventListener而不是弃用的onclick

&#13;
&#13;
document.getElementById("btn").addEventListener("click", function(){
    var select = document.getElementById("result");
    var selectedOption = select.options[select.selectedIndex].value;
    console.log(selectedOption);
     //I've commented this line just for demonstrating purpose
    //window.location.href="deleteresult.php?did=" + selectedOption; 
});
&#13;
<select id="result">
    <option id="option1" value='1'>option 1</option>
    <option id="option2" value='2'>option 2</option>
    <option id="option3" value='3'>option 3</option>
</select>
<a href="#" class="btn dropdown-toggle" id='btn'>Delete </a>
&#13;
&#13;
&#13;

其他选项是使用Javascript&#39; localStorage()或PHP&#39; $_SESSION

在页面上,您将被重定向,您可以使用以下命令获取用作$ _GET参数的值:

 echo $_GET['did'];

答案 2 :(得分:1)

要使用deleteresult.php页面上的变量,你应该有一些这样的代码

$get_did = $_GET['did'];