通过将php数组传递给javascript函数来填充下拉列表onload [英] populate dropdown onload by passing php array to javascript function
问题描述
im试图将php数组传递给javascript函数onload,它将在下拉列表中显示js数组,但现在我已经做过一段时间了,我想我需要再次弹出它
im trying to pass a php array to javascript function onload that will display the js array in a drop down list but now im already doing it for sometime i guess i need to pop it again
首先,我使用此代码将其从一个php文件传递到另一个
first i pass it from one php file to another using this code
header("location: Rules.php?varFields=".serialize($varFields));
第二次我转移到另一个变量,因为它已经传递到了上述php文件中
secondly i transfer to another variable as it had been passed to the said php file
<?php
$varArray = unserialize($_GET['varFields']);
?>
第三部分试图将其传递到jS函数中,然后将其显示在下拉列表中
third part is im tyring to pass it into a jS functon that will then display it to a drop down list
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
这是外部javascript代码
and here is the external javascript code
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.stringify(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in varDisplay)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
对于前两个部分,我已经对其进行了测试,并且可以正常工作,但是对于最后一部分,我无法使其正常工作
for the first two part i already tested it and it is working but for the last parts i cant make it work
推荐答案
我认为这部分看起来可疑
I think this part looks suspicious
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
也许
<body id="body" onclick="cmbRuleField(<?php echo json_encode($varArray);?>)">
更像它.
另一个提示,您可以在呈现的页面上看到输出,以确定写出的代码是什么样的.因此,如果您看到类似以下内容的话:
One more tip, you can see the output on the rendered page to determine what the written out code looks like. So if you see something like:
<body id="body" onclick="cmbRuleField('['a', 'b']')">
您知道有问题.您希望像这样传递本机Javascript数组
you know there is a problem. You want a native Javascript array to be passed like this
<body id="body" onclick="cmbRuleField(['a', 'b'])">
编辑
聊天后,很明显,OP的代码顶部也需要进行调整.
After talking on chat it became clear the top portion of OP's code needed a tweak as well.
header("location: Rules.php?varFields=".http_build_query($varFields));
这篇关于通过将php数组传递给javascript函数来填充下拉列表onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!