将变量传递给 .txt 文件

Pass variable to .txt file

我正在尝试将变量从 html 表单传递到 .php 脚本,然后从 .php 脚本传递到 .txt 文件,其中变量值为存储。问题是,当我测试脚本而不是发布变量号时,它只是发布变量名 "numberVariable".

html/javascript

    <form id="payment-form" action="chargeCard.php" method="POST" name="payment-form">
                            <input onkeypress="return isNumberKey(event)" type="text" name="amount" id="amount" />
                            <input type="hidden" id="numberVariable" name="numberVariable" value="numberVariable"/> <!--this is where I try to pass the variable to the .php script-->
                            <input type="image"  src="Button1.png" id="customButton" value="pay" alt="button"/>

                            </form>

    <script type="text/javascript">
                            function isNumberKey(evt)
                        {
                        var charCode = (evt.which) ? evt.which : event.keyCode
                        if (charCode > 31 && (charCode < 48 || charCode > 57))
                        return false;

                        return true;
                        }
                        </script>

<script type="text/javascript"> 

                            var numberVariable= 1; //this is the variable I am trying to pass to the .php script to then pass the value to the .txt file

                            document.getElementById("numberVariable").innerHTML = numberVariable;
                            document.getElementByID("numberVariable").value = numberVariable;

                        </script>

php

<?php 

    require_once('./stripe-php/init.php');

    \Stripe\Stripe::setApiKey("removed for safety");

    $token = $_POST['stripeToken'];
    $myAmount = $_POST['amount'];
    $describtion = $_POST['description'];

    $numberVariable= $_POST['numberVariable']; //this is where I get the variable from the form

    $myAmount = round((int)$myAmount*100,0);

    try {
    $charge = \Stripe\Charge::create(array(
    "amount" => $myAmount,
    "currency" => "usd",
    "source" => $token,
    "description" => $describtion));

    //PASTE VARIABLE TO .TXT FILE START

    $filename = "iPhoneAuctionBids.txt";
    $content = file_get_contents($filename);
    $content .= $numberVariable. PHP_EOL;
    file_put_contents($filename, $content);

    //PASTE VARIABLE TO .TXT FILE END

    } catch(\Stripe\Error\Card $e) {
    }

?>

您必须实际打开文件并将新数据写入其中。你所做的只是用文件名设置一个局部变量,而不是打开它,也不是获取内容。 http://php.net/manual/en/function.fopen.php 是您需要先阅读的内容。

您没有对该文件进行任何操作。

您需要打开文件并将该值写入其中。

$filename = "iPhoneAuctionBids.txt"; 
$content = file_get_contents($filename);
$content .= $numberVariable . PHP_EOL;
file_put_contents($filename, $content);

另外,在对 DOM 进行任何 js 处理之前,您可能希望等待生成 html。把你的JS代码放在里面

window.onload(function(){
// here
});