简体   繁体   English

HTML变量和文本值传输到PHP / javascript?

[英]HTML variable and text value transfer to PHP/javascript?

So this is what i have in html: 所以这就是我在html中的内容:

    <p><br><form name="edit" method="post">
        <div><select name="Edi" id ="Edi" >
        <option selected="selected">Select</option>
        <option value="1.php">Apple</option>
        <option value="1.php">Bannana</option>
        <option value="2.php">Carrot</option>
        </select>
            <input onclick="return Edit();" type="submit" value="Edit"/></div>
    </form>

here is the corresponding javascript: 这是相应的javascript:

function Edit(){
    if(document.forms['edit'].Edi.value == "Select")
        {
            alert("Please Select Edit Field");
            return false;
        }
    else
    {
        window.open(Edi.options[Edi.selectedIndex].value);
        return true;
    }
}

Here is my problem. 这是我的问题。 As you can see both my option Apple, and Bannana open the same php page. 如您所见,我的选择Apple和Bannana都打开了相同的php页面。 I want that. 我要那个。 But i also want a variable in PHP that can store Apple/Bannana depending which was chosen in dropdown. 但是我还想要PHP中的一个变量,该变量可以存储Apple / Bannana,具体取决于在下拉列表中选择的变量。 I tried this in PHP and it did not work. 我在PHP中尝试了此方法,但没有成功。

 $Table = $_POST['Edi'];

I know i can create a different PHP page for Apple(1.php) and Bannana(3.php). 我知道我可以为Apple(1.php)和Bannana(3.php)创建一个不同的PHP页面。 But in my program creating a page will just be duplicated code. 但是在我的程序中,创建页面将只是重复的代码。 (Apple and bannana just decide which table to store in). (Apple和bannana决定要存储在哪个表中)。 Also, i might be adding more options in the future, so i dont want to keep copying code. 另外,我将来可能会添加更多选项,所以我不想继续复制代码。

What i came up with is putting the variable in javascript, but then tranfering to PHP is not possible. 我想出的是将变量放入javascript中,但随后无法转移到PHP。 So I decided with creating extra layer rather than creating copied pages. 因此,我决定创建额外的图层,而不是创建复制的页面。 (1 selected-shows apple, bananna) (2 selected-shows carrot). (1个选择显示苹果,香蕉)(2个选择显示胡萝卜)。 I can do this. 我可以做这个。

But is this the most efficient way of doing this? 但这是最有效的方法吗?

You can use PHP's $_GET array to access URL parameters. 您可以使用PHP的$_GET数组访问URL参数。

For example: 例如:

<option value="1.php?table=apple">Apple</option>
<option value="1.php?table=banana">Banana</option>

And your PHP: 而你的PHP:

$table = $_GET['table'];

If the variable could be missing, you can provide a default value by using PHP's ternary operator : 如果变量可能丢失,则可以使用PHP的三元运算符提供默认值:

$table = isset($_GET['table']) ? $_GET['table'] : 'apple';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM