2017-09-30 103 views
-2

I 2文件:grampermol.php和kemi.html。在kemi.html中,我调用了一个JavaScript函数,它在按下按钮时运行grampermol.php文件。我遇到的问题是,我无法从位于html文件中的php中的输入字段获取值。在单击<button>后,从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(); 
?> 

我得到一个错误,指出molar_mass不存在。

回答

0

要做到这一点,你需要一个Ajax jQuery的call.You必须先了解PHP是一个服务器端语言和JavaScript/jQuery的客户端side.At下面你的代码将首先看到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 

如果(isset($ _ POST [ '数据'])){

$ formula = $ _POST ['data']; echo json_encode($ formula);

} ?>

+0

谢谢你了很多,现在完美的作品。 –

0
<!-- 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(); 
?> 
相关问题