Php 无需刷新即可提交表单的最简单方法

Php 无需刷新即可提交表单的最简单方法,php,javascript,ajax,forms,webforms,Php,Javascript,Ajax,Forms,Webforms,我一直在尝试创建一个简单的计算器。使用PHP,我成功地从输入字段和跳转菜单中获取了值,当然表单在提交时会刷新 使用Javascript我试着使用 function changeText(){ document.getElementById('result').innerHTML = '<?php echo "$result";?>' 函数changeText(){ document.getElementById('result')。innerHTML='' 但在点击按钮后,它会继

我一直在尝试创建一个简单的计算器。使用PHP,我成功地从输入字段和跳转菜单中获取了值,当然表单在提交时会刷新

使用Javascript我试着使用

function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
函数changeText(){
document.getElementById('result')。innerHTML=''
但在点击按钮后,它会继续给出“0”的答案,因为它无法从POST获取值,因为表单尚未提交

因此,我试图通过ajax或类似的方式找到最简单的方法

或者使用JavaScript获取跳转菜单上的选定值


我在网上读过一些ajax示例,但它们非常混乱(不熟悉该语言)

最好的方法是使用ajax和jQuery

在您的头脑中包含jQuery库之后,请使用以下内容

$('#someForm').submit(function(){
   var form = $(this);

   var serialized = form.serialize();

   $.post('ajax/register.php',{payload:serialized},function(response){
       //response is the result from the server.
       if(response)
       {
           //Place the response after the form and remove the form.
           form.after(response).remove();
       }
   });
   //Return false to prevent the page from changing.
   return false;
});
你的php就是这样

<?php
    if($_POST)
    {
       /*
           Process data...
       */


       if($registration_ok)
       {
           echo '<div class="success">Thankyou</a>';
           die();
       }
    }
?>

使用+组合提交类似以下内容的表单:

test.php:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>

<form action='_test.php' method='post' class='ajaxform'>
 <input type='text' name='txt' value='Test Text'>
 <input type='submit' value='submit'>
</form>

<div id='testDiv'>Result comes here..</div>
<?php
      $arr = array( 'testDiv' => $_POST['txt'] );
      echo json_encode( $arr );
?>

我使用一个新窗口。保存时,我打开一个新窗口,处理保存并关闭onload

window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
php文件将包含一个带有onload=“window.close();”的bodytag,在这之前,还有一个保存编辑器内容的php脚本


它可能不是很安全,但它很简单,就像你要求的那样。编辑器可以保存它的撤销信息等。

阅读我的帖子,然后看看jQuery,它对初学者来说非常好+1,很好的解释。如果你想要一个更懒的方法,它很好。它甚至可以处理文件上传,这是经典Ajax无法做到的。我同意这个插件,wil我帮他开始。这个插件很棒,非常有用。我非常喜欢这段代码,但我不知道如何从帖子中获取数据。
alert(序列化)
给了我“user=john”,但在php文件“echo$\u post”(“user”)中59440。
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');