【问题标题】:Php file fetching data from html file input field after <button> is clicked单击 <button> 后,从 html 文件输入字段中获取数据的 PHP 文件
【发布时间】:2017-09-30 11:36:38
【问题描述】:

我有 2 个文件:grampermol.php 和 kemi.html。在 kemi.html 中,我调用了一个 javascript 函数,该函数在按下按钮时运行 grampermol.php 文件。我遇到的问题是,我无法从位于 html 文件中的 php 输入字段中获取值。

kemi.html 按钮功能:

<input type="text" name="molar_mass" id="molar_mass" placeholder="Fx CH4" size="20">
<br>
<button style="margin-bottom: 1em; margin-top: 1em;" name="BUTTON_1" onclick="gramsPerMole()" type="submit" class="btn btn-success">Beregn</input>

grampermol.php:

<?php

function calculate() {
   $formula = $_POST['molar_mass'];
}

calculate();
?>

我收到一条错误消息,提示摩尔质量不存在。

【问题讨论】:

    标签: javascript php html input interaction


    【解决方案1】:

    为此,您需要一个 ajax Jquery 调用。您必须首先了解 php 是一种服务器端语言,而 javascript/jquery 是一种客户端语言。在下面的代码中,您将首先看到 kemi.html 代码。如您所见当您设置输入值然后单击按钮时,Jquery 代码通过 ajax post 方法获取输入值并将其发送到 grampermol.php 页面。当您有一个有效的后超全局变量值时,在 grampermol.php 页面您得到它然后通过 json_encode() 函数回显它。回显变量发送回 .done ajax 方法并 alert() 它。 kemi.html 代码:

     $(document).ready(function (){
           $('#grams').on('click',function (){
           var a=$('#molar_mass').val();       
           $.ajax({
               url: "grampermol.php",
               method:'POST',
               dataType: 'JSON',
               data:{data:a}})           
                       .done(function( msg ) {
               alert( "Data Saved: " + msg );
           
        });
           
       });
       }); 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" name="molar_mass" id="molar_mass" placeholder="Fx CH4" size="20">
    <br>
    <button style="margin-bottom: 1em; margin-top: 1em;" name="BUTTON_1" id="grams" type="submit" class="btn btn-success">CLICK</button>

    grampermole.php 代码:

    <?php
    if(isset($_POST['data'])){
    
       $formula = $_POST['data'];
       echo json_encode($formula);
    
    }
    ?>
    

    【讨论】:

      【解决方案2】:
      <!-- html form  file -->
      <!-- i dont know how your  gramsPerMole() is so this is what i can help you with tell me if it works-->
      
          <form action="grampermol.php" method="post">
          <input type="text" name="molar_mass" id="molar_mass" placeholder="Fx CH4" size="20"><br>
          <button type="submit" style="margin-bottom: 1em; margin-top: 1em;" name="BUTTON_1" onclick="gramsPerMole()"  class="btn btn-success"> Beregn </button>
      

          <!--grampermole.php file -->
          <?php
          function calculate() {
             $formula = $_POST['molar_mass'];
           return;`enter code here`
          }
           calculate();
       ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多