您将如何使用多种形式设计此网页?

时间:2016-05-23 12:53:20

标签: javascript php

我目前有一个简单的php / html页面只有一个表单,用户输入一个数字,然后页面加载自己(但这次带参数)。

一些关键代码行:

<form action="index.php" method="get">
  <input type="text" name="name">
  <input type="submit" value="Submit">
</form>


<?php
  if (!isset ($_GET["name"])) { 

    echo "<div> Adding some content related to the input </div>";
  } 
?>                                                  

现在我期待添加3个字段,并为每个表单拆分我的页面。 用户应该可以单独使用4个表单,我不希望每次都重新加载页面。我不确定如何设计这个页面 - 我应该重新编写我的页面并使用JS吗?

我有PHP的基础知识,有点用JS。我将能够谷歌我需要的大部分东西,但首先我需要一个正确的方向:)谢谢!

3 个答案:

答案 0 :(得分:0)

您可以将AJAX用于此目的......

$(document).ready(function() {

// process the form
$('form').submit(function(event) {

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'process.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })
        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

答案 1 :(得分:0)

如果您不希望在每次互动之间重新加载页面,则必须使用AJAX。

如果你遇到问题并且想要选择只用PHP(带页面重新加载),你可以很容易地在一个页面上处理多个表单 - 我首选的方法是在名为“action”的表单中设置一个隐藏值设置价值与价值当页面加载时再次读取此内容,例如:

 <?php if(isset($_POST['action']))
{
    $action = $_POST['action'];


    switch ($action)
    {
        case 'hello':

                echo 'hello';

        break;  



        case 'bye':

                echo 'bye';

        break;  


    }

}

?>


<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>

</form>



<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>

</form>

然后,每当用户与每个表单进行交互时,每次保持更新时,您都可以保存并回显每个表单的值。

AJAX是更好的解决方案

答案 2 :(得分:-1)

如果您不想在每次提交每个表单时重新加载页面,那么您应该使用Ajax来调用您的api。你在PHP中编写单独的api,然后在Jquery的Ajax中调用该api。

此处不会重新加载页面。您也可以在每次点击按钮时调用ajax。