首页 > 解决方案 > 一次请求表单和 POST?

问题描述

请原谅可怜的标题。我是一个完全的初学者,不知道如何让它变得更好。

我正在尝试使用 PHP 发布表单数据。我的问题是,在我发布表单数据之前,我需要从表单中获取一个值,每次我请求页面时都会改变。
请注意第二个输入,该值是自动生成的,并且每次我请求表单时都是一个随机数
这是我的form.php:

<?php 

if(!isset($_REQUEST['submit_btn'])){
echo '  
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
   <input type="text" name="user_name" id="user_name">
   <input type="hidden" name="a_random_password" value="'.(rand(10,100)).'">
   <input type="submit" value="submit" name="submit_btn">
</form>';

}

if(isset($_REQUEST['submit_btn']))
    {
       $user_name= $_POST["user_name"];
       $a_random_password = $_POST["a_random_password"];

       echo "Your User Name is:". $user_name;
       echo "<br> and your Password is : $a_random_password;

    }

?>

还有我的 post.php

<?php
$url = "http://test.com/form.php";

$data = array(
'user_name' => 'John',
'a_random_password' => 'xxx',
'submit' => 'submit'
);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',    
        'content' => http_build_query($data)        
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Error"; }

var_dump($result);

?>

那么我如何获取 a_random_password 值并将其与表单一起提交到单个请求中,否则密码将不适合用户名。

标签: phppost

解决方案


Sup,你想要做的是不可能以这种方式使用 PHP,因为 PHP 的唯一工作就是在服务器端呈现你的内容。要收听客户端,您需要使用 javascript。

    let randomPassword = document.getElementById('a_randow_password')
    let name = document.getElementById('name')
    let password = document.getElementById('password')
    
    name.onkeyup = function(){
        password.value = randomPassword.value + name.value
    }
<input type="text" id="name" name="user_name" placeholder="name"><br />
<input type="hidden" name="a_random_password" id="a_randow_password" value="xxx">
<input type="text" id="password" placeholder="password"><br />


推荐阅读