【问题标题】:Get a value out of a php array in a js function从 js 函数中的 php 数组中获取一个值
【发布时间】:2022-10-22 18:56:37
【问题描述】:

我对此很陌生。我正在尝试以下。我在 productionCalculator.php 中有一个选择输入下拉菜单。每当输入发生变化时,我都会调用一个 js 函数。这个函数需要一个 php 文件中的数组。我已经学到了很多东西(就像我必须使用 include 而不是 require f.e.)但我得到的唯一“价值”是空的。当我直接在被调用的 php 文件中定义一个字符串变量时,它可以工作,但是如果我在另一个 php 中访问该数组,则返回值为 null。而且我不能直接调用数组php文件,因为echo会把结果写在网站上。我真的被困住了。请帮忙,我非常感谢你。

涉及4个文件:

productionCalculator.php 中的选择

<body>
        <img src="https://images.evetech.net/types/1002/bp" id="bpoImage">
            <select name="bpoDropdown" id="bpoDrop" onchange="SetBpoImage()">
            <?php 
            foreach ($blueprintDict as $key => $value) { ?>                
                <option value=<?php echo $key?>><?php echo $key?></option>
                <?php 
            }
        ?>
        </select>
    </body>

下拉列表更改时调用的 js 函数。这是一个 .js 文件

function SetBpoImage()
{
    var e = document.getElementById("bpoDrop");
    var index = e.selectedIndex;

    var req = new XMLHttpRequest(); 
    req.onload = function() {
    console.log(this.responseText); 
    };
    req.open("get", "assets/getBlueprintDict.php", true); 
    req.send();
}

getBlueprintDict.php

<?php
require("assets/blueprintDict.php");
echo json_encode($blueprintDict); 
?>

还有我在js函数中需要的blueprintDict.php。

<?php 
$blueprintDict=array(
"Typhoon" => 1,
"Dominix" => 2,
"Erebus" => 3,
"Small Shield Extender I" => 4,
"Survey Scanner I" => 5,
);
?>

文件夹结构: 主文件夹

资产文件夹

【问题讨论】:

  • 检查代码中的路径。在我看来,assets/getBlueprintDict.php 期待找到assets/assets/bluebpintDict.php
  • 资产/资产?但它说 require("assets/blueprintDict.php");什么是正确的路径。尽管如此,我用资产/资产尝试了它,令人惊讶的是没有错误,但仍然返回 null。 echo json_encode($blueprintDict);有效,它只返回 null
  • 它需要assets\blueprint.php,但这是相对于getBlueprint.php 的工作目录的路径,即assets。我不知道正确的路径应该是什么 - 你还没有发布你的文件夹结构。
  • 好的,我将文件夹结构添加到帖子中
  • 你试过require("blueprintDict.php");getBlueprintDict.php?请参阅:include: check in the calling script's own directory

标签: javascript php html arrays


【解决方案1】:

首先让我们为您解决一些问题 请注意我到目前为止所做的更改

Foreach 错误(固定版本)

        <img src="https://images.evetech.net/types/1002/bp" id="bpoImage">
            <select name="bpoDropdown" id="bpoDrop" onchange="SetBpoImage()">
            <?php 
            foreach($blueprintDict as $key => $value) {               
                echo '<option value="'.$key.'">'.$key.'</option>';
            }
        ?>
        </select>
    </body>

您的 blueprintDict 有错误 (虽然这有时会被忽略但不应该如此

$blueprintDict=array(
"Typhoon" => 1,
"Dominix" => 2,
"Erebus" => 3,
"Small Shield Extender I" => 4,
"Survey Scanner I" => 5
);
?>

blueprintDict 中的最后一项有一个“,” 这违反了PHP的法律

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    相关资源
    最近更新 更多