如何从PHP获取数组并使用数组中的值?

时间:2016-06-24 20:20:19

标签: javascript php html arrays

我在index.html中有一个下拉菜单和javascript。为清楚起见,我删除了大多数选项(超过20个)。它将下拉菜单选项发送到engine.php

的index.html

<script>
function refreshpage(e)
{   
    var e = document.getElementById("sr");
    var snk = e.options[e.selectedIndex].value;
    window.location.href = "engine.php?selectedOption=" + snk;
}
</script>

<h4>Select your option</h4>
    <form action="" id="optionform" onsubmit="return false;">
        <select class="item_options" id="sr" name='sr' onchange="refreshpage(this);">
             <option value="None">Select option</option>
             <option value="Option1">Option 1</option>
             <option value="Option1">Option 2</option>
             <option value="Option1">Option 3</option>
        </select>
    </form>

当您选择一个选项时,它会将选项发送到engine.php

engine.php

<?php
$option1 = 5;
$option2 = 10;
$final = array($option1, $option2);
if($_GET["selectedOption"] == 'Option1')
{
    $option1 = 20;
    $option2 = 20;

}
?>

如何将$final发送回index.html并使用javascript来使用$final数组($option1$option2)中的值。我基本上想要刷新index.html并使用新的更新值($option1 = 20; $option2 = 20;

4 个答案:

答案 0 :(得分:1)

您可以使用ajax作为@Hackerman建议,并且可能是我将使用的方法。

或者,您可以在engine.php页面的末尾添加重定向,并将用户发送回索引页面。

$newURL = "index.php?values=$newValues";
header('Location: '.$newURL);

要采用这种方法,您的索引页面需要在加载时处理values参数。

答案 1 :(得分:1)

如果您不关心网址是什么,可以{em> engine.php 中的 index.html {/ 1>:

require

index.html 中的一些PHP内容:

<?php
$option1 = 5;
$option2 = 10;
$final = array($option1, $option2);
if($_GET["selectedOption"] == 'Option1')
{
    $option1 = 20;
    $option2 = 20;

}
require('index.html')
?>

您可以在任何地方使用<script> function refreshpage(e) { var e = document.getElementById("sr"); var snk = e.options[e.selectedIndex].value; window.location.href = "engine.php?selectedOption=" + snk; } </script> <?php if ( isset($final) { print_r($final); } ?> <h4>Select your option</h4> <form action="" id="optionform" onsubmit="return false;"> <select class="item_options" id="sr" name='sr' onchange="refreshpage(this);"> <option value="None">Select option</option> <option value="Option1">Option 1</option> <option value="Option1">Option 2</option> <option value="Option1">Option 3</option> </select> </form> 标记,只需记住此部分将在服务器上处理,并仅将HTML和JavaScript发送到浏览器。

答案 2 :(得分:1)

您可以使用 ajax 来来回发送数据。使用 jquery ,您可以执行以下操作:

var final;
$.ajax({
    url: 'engine.php',
    data: { selectedOption: $('#optionform').find(":selected").text() },
    dataType: 'json',
    success: function(data) {
        final = data;
    }
});

然后在engine.phpecho json_encode($final);

答案 3 :(得分:0)

这只能使用AJAX完成。 将AJAX发送到somepage.php,其中返回带有$ final的json。 做了之后。