无需刷新即可提交表单的最简单方法 [英] Easiest Way To Make A Form Submit Without Refresh

查看:32
本文介绍了无需刷新即可提交表单的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.

使用我尝试使用的 Javascript

Using Javascript i tried using

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

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

but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.

所以我正在尝试通过ajax或类似的东西找出最简单的方法

So I am trying to work out either the Easiest Way to do it via ajax or something similar

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

or to get the selected values on the jump menu's with JavaScript.

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

I have read some of the ajax examples online but they are quite confusing (not familiar with the language)

推荐答案

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

Use jQuery + JSON combination to submit a form something like this:

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>

_test.php:

<?php
      $arr = array( 'testDiv' => $_POST['txt'] );
      echo json_encode( $arr );
?>

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;
    });

});

这篇关于无需刷新即可提交表单的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆