簡體   English   中英

如何在第二頁上將值從Javascript傳遞給php變量?

[英]How to pass value from Javascript to php variable on the second page?

我有兩頁。 接受輸入並將其存儲到javascript變量的接收器。 另一個將接收發送的變量並將其存儲到php變量,以便我可以將其轉發到數據庫。

這是我的第一頁的代碼:

<html>
<head>
    <script type="text/javascript">
        var pricee= 0;
        var quants;
        function queue(num,str){
            this.pricee=num;
            this.quants=str;
            alert(num+" "+str);
        }
        function alertCurrentNumandStr(){
            alert("This is the latest: "+this.pricee+" "+this.quants);
        }
        function send(num){
             this.pricee=num;
        }
    </script>
</head>
<body>
    <ul>
        <li><script type="text/javascript">var x=42, y="alive";</script><a href="#" onclick="queue(x, y);">42 Alive</a></li>
        <li><a href="#" onclick="alertCurrentNumandStr();">Get</a></li>

        <li><script type="text/javascript">var t=10;</script><a href="#" onclick="send(t);">Submit</a></li>
        <!--How to send this.pricee, this.quants to .php when clicking the Submit link(above)?-->
    </ul>
</body>
</html>

和我的第二頁上的代碼:

<html>
<head>
<?php
    $testNum= $_GET['pricee']
?>
</head>
<body>
<?php
       echo "<h1>The num value </h1>";
       echo $testNum;
?>
</body>
</html>

單擊“提交”后,如何將javascript變量傳遞到第二頁?

您也可以使用簡單的GET變量執行此操作。

  1. <a href='yourphpfilename.php?price1=xxx&YOUR2ndvariable=xxx'>Click this</a>
  2. 通過轉發到下一個php頁面,使用簡單的獲取此變量

    $ _GET [ '價格1']; ...

將您的發送功能更改為此

  function send(quants){
window.location.href = "yourPhpPageUrl.com?price"+pricee+'qunatity' +quants;
            }

你的PHP file沒有變化。 試一試吧

把你的li標簽放在form標簽中,如下所示:

<form action="action_page.php" method="GET">
    <ul>
        <li><script type="text/javascript">var price1=12, itn1="Mar";</script><a href="#" onclick="queue(price1, itn1);">Marinated $12</a></li>
        <li><script type="text/javascript">var price2=1, itn2="Kalamay";</script><a href="#" onclick="queue(price2, itn2);">Kalamay $1</a></li>
        <li><script type="text/javascript">var price3=5, itn3="coach Yeng";</script><a href="#" onclick="queue(price3, itn3);">Coach Yeng $5</a></li>
        <li><a href="#" onclick="getPrice();">Get</a></li>

        <li><script type="text/javascript">var quantity=10;</script><a href="#" onclick="send(quantity);">Submit</a></li>
    </ul>
<input type="text" name="pricee" value="100">
<br>
Pricee:<br>
<input type="submit" value="Submit">
</form>

我假設你的php頁面是action_page.php

這里method = "GET"告訴php頁面它必須接收值為get request。

除此之外,在結束form標記之前input type="submit"表示您正在使用submit事件來發送li標記中的值。

您在PHP代碼中使用了pricee標簽( $_GET("pricee") )。 要匹配此請求,您必須擁有name="pricee"的元素。

我在上面添加了這個標簽。

暫無
暫無

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

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