在JavaScript函数中从php生成的表单获取输入值

时间:2013-10-11 02:23:06

标签: javascript php html forms

可能使我的代码过于复杂。 我有两个单选按钮表单,这些表单是在JavaScript onclick函数中动态生成的:

function displayForm(){

document.getElementById("buildlist").innerHTML = '<?php
    echo '<form id="MB" name="MB" method="GET">';
    while ($row = mysql_fetch_assoc($mbquery_run))
        {
        echo '<input type="radio" class="'.$row['socket'].'" name="MB" value="'.$row['model'].'"><a href="'.$row['link'].'" class="radiolinks" target="_blank">'.$row['model'].'</a><br>';
        }
    echo '<input type="radio" class="dunno" name="MB" value="dunno">Don't know';
    echo '</form>';
        ?><br><br>';}

这是代码的一部分,我有另一个这样的函数用于另一个无线电表单。这非常有效。我需要保存输入以供以后使用。所以我创建了一个onclick JS函数,目的是使用PHP输出选项(然后可能将它存储在数据库中),如下所示:

function submitInput(){
<?php
        if (isset($_GET['MB']) && isset($_GET['CPU']))
    {
    $MB = $_GET['MB'];
    $CPU = $_GET['CPU'];
    print $MB;
    print $CPU;
    }
    else{
        $hey = "11111111111111111111111111111111111111111";
        echo ''.$hey.'';
    }?>}

这不起作用,我甚至没有从else检查获得$ hey的输出。我对编程很新,这可能有点超出了我的联盟。我正在考虑将输入存储在会话变量中。考虑到目前的功能,这是一个可行的选择吗? 帮助非常赞赏!

P.S:如果你想知道,表单输出和mySQL查询工作正常,问题是在第二个函数中从PHP获取输入。

3 个答案:

答案 0 :(得分:0)

我假设您在提交表单时使用“发布”操作?如果是这种情况,则需要将$ _GET变量更改为$ _POST。

$ _ GET用于将变量追加到要解析的URL的位置。 $ _POST接受通过表单提交的输入。

同样重要的是要注意,您无法使用javascript将PHP代码编写到您的页面。 PHP需要在服务器上处理并传送到您的浏览器。你不想做什么。

您需要废弃代码并重新开始,更好地了解HTML / PHP / JS如何协同工作。

答案 1 :(得分:0)

PHP是服务器端,这意味着它在服务器上执行,这意味着php标签内的所有内容都在服务器上完成,然后在纯HTML上传送到客户端(浏览器)......

Javascript是客户端,这意味着它只处理浏览器上已有的东西,有些技术可以在服务器上使用javascript(例如node.js),但这里没有相关性。

你要做的是使用php写一部分javascript函数,这既错又疯狂。

你应该完全理解这些概念。

但无论如何,这就是我在这种情况下会做的事情:

PHP代码:

<?php

    function createForm(){
        echo: '<form id="MB" name="MB" method="GET" action="yourphpfile.php">'; //it's your choice, but i prefer to use POST methods on forms and add the action property pointing to your php.file
        while ($row = mysql_fetch_assoc($mbquery_run)){
            echo '<input type="radio" class="'.$row['socket'].'" name="RADIO" value="'.$row['model'].'">"'; //keep names and ids unique for easy access. (form and input share the same name)
            echo "<a href="'.$row['link'].'" class="radiolinks" target="_blank">'".$row['model']."'</a>"
            echo "<br>'";
        }
        echo '<input type="radio" class="dunno" name="RADIO" value="dunno">Don''t know';
        echo '<input type="submit" id="btnSubmit" value="Submit" />' //your form doesn't have a submit button
        echo '</form>';
    }

    function readFormData(){
        var radioValue = $_GET["RADIO"];
        //or if it's a POST
        var radioValue = $_POST["RADIO"];
    }

    //this should be ok
    if (isset($_GET['RADIO'])){ //only will work if form method is GET
        readFormData(); //execute the function if a parameter is found
    }

    //but this is the way to go (imho)
    if($_SERVER['REQUEST_METHOD']=='POST'){ //only will work if form method is POST
        readFormData();
    }

    createForm(); // create the form 
?>

Javascript代码:

NONE

在您的示例中,您没有提交按钮,您需要做的就是有一个提交按钮,用于将数据发布回服务器,然后您可以检索所选择的无线电按钮...

如果你想在这个例子中使用javascript,我认为没有必要,除非你想使用som ajax调用,所以使用javascript你会得到所选的radiobuttons的值,然后通过ajax将这些值发送到服务器,做你的工作,并通过警报或类似的东西通知用户......

希望它有助于交配。欢呼声。

答案 2 :(得分:0)

好的,这是一个完全有效的例子,它当然不会访问mySql数据库,但它会创建一个包含数组动态数据的表单。

它还将确定是否存在名为hide的url参数,例如index.php?hide = 1, 此参数将导致表单被隐藏并显示一个按钮,此按钮将由javascript触发以显示表单。

此外,它会在表单发布后从表单中读取值。

希望这能让事情顺利,毫无疑问。

<!doctype html>
<html>
    <head>
        <title>Testing!</title>
    </head>
    <body>
        <h2> This is a test </h2>
        <hr/>
            <?php
                //this function creates the form
                function createForm(){
                    if(isset($_GET["hide"])){ //checks if a url parameter called hide exists
                        //if the parameter exists, lets hide the form
                        $isHidden = "style='display:none;'";
                        //and create a button to display the form
                        echo "<input type='button' id='btnShowForm' value='Show Form' />";
                    }else{
                        $isHidden = "";
                    }
                    $data = ["hello", "world"]; //simulated data
                    $i = 0;
                    $dataLength = count($data)-1;
                    //this is the form
                    echo "<form id='frmTest' name='frmTest' method='POST' action='index.php' ".$isHidden.">";
                    while ($i <= $dataLength){
                        echo "<p>";
                            echo "<input type='radio' name='RB' value='".$data[$i]."'/>";
                            echo "<label>".$data[$i]."</label>";
                        echo "</p>";
                        $i++;
                    }
                    echo "<input type='submit' value='Submit Form' />";
                    echo "</form>";
                }
                //this function reads the data from the form on POST
                function readFormData(){
                    if(isset($_POST["RB"])){ //if the page is requested as a POST
                        $radioValue = $_POST["RB"]; //read the RB value inside the POST data
                        if(isset($radioValue)) //if there's data on the variable let's display it
                            echo "selected value: ".$radioValue;
                        else
                            echo ":(";
                    }
                }

                if($_SERVER['REQUEST_METHOD']=='POST'){ //check if it's a post
                    readFormData(); //read the data
                }else{
                    createForm(); //create the form
                }
            ?>

    </body>
    <script>
        var btn; //holder for the button (if exists)
        window.onload = function(){ //when the page is fully loaded, jquery's $(window).load
            btn = document.getElementById("btnShowForm"); //store the button, jquery's $("#btnShowForm")
            if(!btn){ return; } //if no button exists, abort, jquery's if(!btn.size())
            if( btn.addEventListener ){ //Every browser (except IE < 9)
                btn.addEventListener("click",  showForm, false); //add a click event to the button, function showForm will be fired on click, jquery's btn.click(showForm);
            }else{ //IE 6,7,8
                btn.attachEvent("onclick", showForm);
            }
        }

        function showForm(){ //function to display the form
            var form = document.getElementById("frmTest"); //holder for the form jquery's $("#frmTest")
            form.style.display=""; //let's show the form jquery's form.show();
            btn.style.display = "none"; //let's hide the button jquery's btn.hide();
        }
    </script>
</html>

正如您所看到的,PHP完全与JS分离,这就是它要完成的方式。

服务器端与客户端无关,但您可以(并且应该)为JS留下痕迹,以便对服务器发送的数据执行某些操作。

让我们总结一下:

PHP - 创建一个表单,并根据url参数隐藏它,如果它被隐藏,那么它将显示一个按钮

JS - 将查找一个按钮,如果它存在则会向其添加一个事件,否则什么都不做。

容易不是吗?。

相关问题