使用jQuery在同一页面上显示表单并获取输入


Show form and get input on the same page, using jQuery

因此,我将尝试描述我正在尝试制作的内容。

表格应出现在顶部。只需一个输入和一个提交按钮。当您单击提交时,会出现一个弹出窗口并显示结果。

这是我的代码:

<html>
    <head>
        <script type="text/javascript">
            $(document).ready(function(){
                $(".show").click(function(){
                $("#popup").fadeIn();
                return false; 
                });
            });
        </script>
    </head>
    <body>    
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
            Number: <input type="number" name="number" />
            <input class="show" type="submit" name="submit" />
        </form>
        <div id="popup">    
            <?php
                if(isset($_POST["number"])) {
                    echo $_POST["number"];
                }
            ?>
              <a id="iks">Close</a>
        </div>
    </body>
</html>

(我删除了<head>的一部分以使其更小,但有一种样式将display:none;表示为#popup

问题是它不会更新:它保持不变。弹出窗口有效,但无论我键入什么,它总是给出相同的数字。

我在没有jQuery的情况下尝试过,它是有效的,所以它与php/html无关。

您的.show是一个提交按钮,但您是点击事件中的return false;(实际上停止了提交,因此不会出现新值)。

我要么将show绑定到一个新按钮,要么使用AJAX提交值,并在返回后在#popup中显示结果。


为了冗余和进一步的解释,这里有一个工作示例和代码:

首先,将其添加到当前PHP文件的顶部:

<?php
  // check if a value is being submitted
  if (isset($_REQUEST['number'])){
    // there is one, output it then exit PHP (so we don't output the
    // rest of the page--an ajax call only needs the response, not
    // the layout)
    echo $_REQUEST['number'];
    exit;
  }
?>

请注意,我不会检查有效值,也不会检查它来自哪个方法。这使您能够将method="POST"更改为method="GET",并使示例仍然有效。否则,您可能希望使用$_POST[] superglobal,同时验证输入

现在,修改您的<script></script>以使用以下内容,而不是您现有的内容:

$(document).ready(function(){
// we want to trigger this function when the form's submitted
$('form').on('submit',function(e){
     // store the form element
     var $form = $(this);
     // make an AJAX call to the action of the form
     // using the method supplied.
     $.ajax({
         'type': $form.prop('method'),
         'url': $form.prop('action'),
         'data': $form.serialize(), // send the value of "number"
         'dataType': 'html',
         'success': function(html){
            // we now have the value back, let's add it to the #popup
            // element, add a close button and then fade both in.
            $('#popup').html(html).append(
                $('<a>',{'href':'#','html':'Close','id':'iks'}).on('click',function(e){
                     $(this).parent().fadeOut();
                })
            ).fadeIn();
        }
    });
    // prevent the form from submitting the traditional way
    e.preventDefault();
});
});

因为上面的内容利用了表单指定的内容(在actionmethod属性中),所以不需要太多的自定义。现在,它将使用AJAX来POST/GET数字输入中的值,因为我们添加了PHP代码,所以数字将被重新输出,success函数将接收它,将它添加到#popup元素(以及一个关闭按钮)并淡入。

好吧,你做得不对。除了显示弹出窗口,您还需要向PHP脚本发送AJAX请求,等待结果,然后在弹出窗口中显示。因此,总结一下您需要的是一个php脚本和一个html文件。它可能看起来像

ajax.php

<?php
if (isset($_POST['number'])){
    echo $_POST['number'];
}

form.html

<html>
<head>
<script type="text/javascript">
    $(document).ready(function(){
        $('#form').on('submit',function(e){
            e.preventDefault();
            $.post('ajax.php', $(this).serialize(), function(response){
                $('#result').html(response);
                $('#popup').fadeIn();
            }
        });
    });
</script>
</head>
<body>
<form id="form" method="post">
    Number: <input type="number" name="number" />
    <input class="show" type="submit" name="submit" />
</form>
<div id="popup">
  <div id="result"></div>
  <a id="iks">Close</a>
</div>
</body>
</html>

客户端代码与服务器端代码混合在一起。所有的PHP都在任何JavaScript之前运行。一旦JavaScript开始运行,PHP就已经运行很久了,在这个页面上不会再做任何事情了。

您必须将Web开发视为一种元编程。也就是说,生成软件的软件。PHP是在服务器上运行并生成要在浏览器中运行的代码。每个HTTP web请求都会运行一次PHP。您的JavaScript是根据浏览器中发生的事情运行的。您的JavaScript对web请求或服务器一无所知。它只知道它所在的页面、浏览器和DOM。同样,PHP对浏览器或JavaScript的作用一无所知。JavaScript和PHP完全独立运行,没有任何交互。

也就是说,在引入AJAX之前。AJAX风格的编程提供了一种让JavaScript与PHP对话的机制。

创建一个专门用于处理AJAX请求的PHP页面。您需要一个单独的页面,因为您不会返回完整的html页面,而是返回少量数据,可能是html,但通常是JSON,也可能是XML。

如果您的Ajax处理程序PHP页面是这样的:

AjaxHandler.php

<?php 
    if(isset($_POST["number"])) { 
        echo $_POST["number"]; 
    } 
?>

然后你可以像这样用ajax验证你的JavaScript:

$(".show").click(function(){ 
    $.post("ajaxHandler.php", { number: $("input[name=number]").val() }, function (response) {
        $("#popup").text(response).fadeIn(); 
    });
    return false;  
}); 

这段代码发出一个http请求,将number=[n]发布到ajaxHandler.php。该响应将提供给回调函数,以便根据需要使用。