簡體   English   中英

如何在javascript中傳遞一個值並在另一個頁面上獲取它?

[英]how to pass a value in javascript and get it on another page?

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變量????

用這個:

 <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> 

首先,你需要在option上有一個值,如:

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

我已經為你做了一個jQuery演示,請看下面的代碼片段:

 $('.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; }) 
 <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> 

一個Javascript替代方法是使用addEventListener而不是棄用的onclick

 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; }); 
 <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> 

其他選項是使用Javascript的localStorage()或PHP的$_SESSION

在頁面上,您將被重定向,您可以使用以下方法獲取用作$ _GET參數的值:

 echo $_GET['did'];

並且為了在deleteresult.php頁面上使用該變量,你應該有一些像這樣的代碼

$get_did = $_GET['did'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM