从Javascript弹出窗口获取值-用作php post值


Grab Value from Javascript popup - use as php post value

首先,是否有更好的方法?让我知道。。。这种方式看起来有点"粗鲁"。以下是我要做的:正如您在下面的input中看到的,我有一个文本字段,我只是想看起来像<a>链接。如果用户单击它,我希望JavaScript弹出框显示用户输入的电子邮件。我希望他们点击ok,然后我将该电子邮件值发送回表单,然后表单通过php帖子提交。

我不知道如何从框中获取值并将其插入form(如果可能的话),以便它可以提交给php

这是代码:

    <form id="frm1" action="login.php" method = "post">
        <input onclick="resetPassword()" type="text" name="email" value="Reset Password" style="cursor: pointer; background:none; text-decoration: underline; border: none;"  />
    </form>

    <script>
        function resetPassword() {
        var x;
        var email=prompt("Enter email to reset password.", "example@email.com");
        if (email!=null)
          {
          document.getElementById("frm1").submit();
          }
        }
   </script>

  <?php 
     if (isset($_POST['email'])) {
         $email = $database -> escape_value(trim($_POST['email']));
        //  reset password    
      }
  ?>

从promt获取电子邮件,将其粘贴到输入字段并提交表单。

<form id="frm1" action="login.php" method='post'>
    <input id="email" onclick="resetPassword()" type="text" name="email" placeholder="Reset Password" />
</form>
<script type="text/javascript">
  function resetPassword() {    
    var email = prompt("Enter email to reset password.", "email@example.com");
    if (email != null) {
      document.getElementById("email").value = email; 
      document.getElementById("frm1").submit();
    }
  }
</script>

更好的方法是使用jQuery,并通过AJAX将文本字段的信息发送到需要$_POST变量的脚本。通过这种方式,<form>元素将是不必要的。

    function resetPassword() {
        var x;
        var email=prompt("Enter email to reset password.", "example@email.com");
        if (email!=null) {
             $.post( url_of_the_script, {email: email}, function() { alert('Email sent'); } );
        }
    }

将ID添加到input字段:

<form id="frm1" action="login.php">
    <input id="email" onclick="resetPassword()" type="text" name="email" value="Reset Password" style="cursor: pointer; background:none; text-decoration: underline; border: none;"  />
</form>
    function resetPassword() {
    var email=prompt("Enter email to reset password.", "example@email.com");
    if (email!=null)
      {
      document.getElementById("email").value = email; // Put value into form field
      document.getElementById("frm1").submit();
      }
    }

如果您不希望用户能够直接在表单字段中键入内容,则应为其指定readonly属性。onclick阻止他们点击它,但他们仍然可以通过选项卡到达那里。