我正在建立一个(最终)成为游戏前端的网站。我希望能够动态构建用户能够购买的“权力”列表。为了构建这些列表,我使用基于PHP的SQL查询,然后将其传递给Javascript以进行动态选择(某些权限具有先决条件权限)。
这是我的代码: Javascript(单独文件)
function upgradeList(passed)
{
var PowerArray = [];
var DetailPowerID = [];
var EscapedPowerID = [];
PowerArray.push([]);
PowerArray = eval(passed);
var OutputThing="";
for (i=0;i<PowerArray.length;i++)
{
DetailPowerID[i] = 'detail' + PowerArray[i][0];
EscapedPowerID[i] = "'" + DetailPowerID[i] + "'";
}
for (i=0;i<PowerArray.length;i++)
{
OutputThing = OutputThing + "<br><a href='#' onClick='showUpgradeDetails(" + DetailPowerID[i] + ")'>" + PowerArray[i][2] + "</a><div class='hidden' id='" +
DetailPowerID[i] + "'>" + PowerArray[i][3] + "</div>"; }
document.getElementById("secondUpgrade").innerHTML=OutputThing;
document.getElementById("secondUpgrade").style.display='block';
}
}
PHP编写HTML和JS: {$ AbleToUpgrade和$ UpgradeList都是从SQL查询构建的二维数组)
echo "<script name='UpgradeList'>";
settype($UpgradesListSize[$i],"int");
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "var UpgradeList" . $AbleToUpgrade[$i][0] . " = new Array();";
for ($j=0;$j<=$UpgradesListSize[$i];$j++)
{
echo "UpgradeList" . $AbleToUpgrade[$i][0] . ".push(Array('"
. $UpgradeList[$i][$j][0] . "', '"
. $UpgradeList[$i][$j][1] . "', '"
. $UpgradeList[$i][$j][2] . "', '"
. $UpgradeList[$i][$j][3] . "', '"
. $UpgradeList[$i][$j][4] . "'));";
}
}
echo "</script>";
......等等......
echo "<div id='SpendUpgrade'>
Select power to upgrade:
<ul>";
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "<li><a href='#' name='UpgradeList" . $AbleToUpgrade[$i][0] . "' onClick='upgradeList(this.name)'>" . $AbleToUpgrade[$i][1] . " - " . $AbleToUpgrade[$i][2] . "</a></li>";
}
echo "</select>
<div id='secondUpgrade' class='hidden'>
</div>
<div id='thirdUpgrade' class='hidden'>
</div>
</div>";
当我加载页面时,我最终会生成如下生成的文本:
<a href="#" onclick="showUpgradeDetails(detail21)">Real Armor</a>
和相应的div:
<div class="hidden" id="detail21" style="display: none;">Your armor only works in the Waking</div>
为了让div显示(display:block;)
,我需要像这样调用函数:
showUpgradeDetails("detail21")
但是我不能让JS / PHP正确地写出引号。请帮忙(有任何或所有这些吗?)!
答案 0 :(得分:0)
我找到了一个解决方案,而不是JSON.parse()
。
我将PowerArray = eval(passed);
更改为PowerArray = window[passed];
。
因为passed
包含变量的名称,而不是变量本身,所以我无法直接使用它。但是,因为它是一个只包含全局定义变量名称的字符串,所以我可以将它传递给window[]
构造并让它工作。