我试过这段代码:
<script type="text/javascript">
var s = 0;
document.getElementById('text').value = "<?php echo phpVal[s];?>";
</script>
问题是如何将(s)值放入(PHP)代码中。
以下是更多背景信息:
<head>
<?php $s = ["a","b","c"]; ?>
<script type="text/javascript">
function doFun(ss){
var data = "<?php echo json_encode($s); ?>";
document.getElementById('t').value = s[ss];
}
</script>
</head>
<body>
<input type="text" id="t" name="t" />
<button type="button" id="b" name="b" onclick="doFun(0)">doFun</button>
</body>
答案 0 :(得分:2)
当s
有值(在客户端上)时,PHP代码(在服务器上)已经很长时间了自完成以来。
取而代之的是很多取决于您的最终目标。你有很多选择。以下是其中两个:
将整个phpVal
数组/对象输出到客户端,然后使用s
将其编入索引。
var s = 0;
var data = <?php echo json_encode(phpVal)%>;
document.getElementById('text').value = data[s];
通过ajax将s
发送到服务器,让PHP代码运行以响应 请求从phpVal
中选择正确的值,然后返回作为ajax的结果,将其放在客户端input
的{{1}}中。例如:
JavaScript的:
value
PHP var s = 0;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('text').value = xhr.responseText;
}
};
xhr.open("get-value.php?s=" + encodeURIComponent(s));
// You don't really need this ^
// for `0`, but many times when sending variables to the
// server, you do
xhr.send();
(粗略):
get-value.php
但这又取决于你实际上要做什么。