使表单无需刷新即可轻松提交

Jam*_*mes 5 javascript php forms ajax webforms

我一直在努力创造一个简单的计算器.使用PHP我设法从POST输入字段和跳转菜单获取值,但当然表单在提交时刷新.

使用Javascript我尝试使用

function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
Run Code Online (Sandbox Code Playgroud)

但是,在点击按钮后,这将继续给出"0"的答案,因为由于表单尚未提交,因此无法从POST获取值.

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

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

我在线阅读了一些ajax示例,但它们很混乱(不熟悉该语言)

Rob*_*itt 7

最好的方法是使用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;
});
Run Code Online (Sandbox Code Playgroud)

你的PHP就是这样.

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


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

  • +1,很好的解释.如果你想要一个更加懒惰的方法,[jQuery表单插件](http://jquery.malsup.com/form/)很不错.它甚至可以处理文件上传,而传统的Ajax则无法处理. (4认同)

Nav*_*eed 7

使用jQuery + JSON组合提交如下表单:

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>
Run Code Online (Sandbox Code Playgroud)

_test.php:

<?php
      $arr = array( 'testDiv' => $_POST['txt'] );
      echo json_encode( $arr );
?>
Run Code Online (Sandbox Code Playgroud)

jsFile.js

jQuery(document).ready(function(){

    jQuery('.ajaxform').submit( function() {

        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        for(var id in data) {
                            jQuery('#' + id).html( data[id] );
                        }
                      }
        });

        return false;
    });

});
Run Code Online (Sandbox Code Playgroud)