在单击PHP / Jquery时更新附加的变量
Update appended variable on click PHP / Jquery
我有一个像这样的数组
<?php
$info = array(
"cat",
"dog",
"bear"
);
?>
我在叠加层上随机输出一个字符串,例如
<script>
var text = '<?php echo $info[array_rand ($info)];?>';
$(function() {
var loading = function() {
var over = '<div id="overlay">' + '<p class="info">' + text + '</p>' + '</div>';
$(over).appendTo('body');
$('#overlay').click(function() {
$(this).remove();
});
$(document).keyup(function(e) {
if (e.which === 27) {
$('#overlay').remove();
}
});
};
$('.wrapper').click(loading);
});
</script>
.CSS:
#overlay {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #000;
opacity: 0.90;
height: 200%;
}
.info{
position: absolute;
width: 100%;
top: 25%;
height: 200px;
font-size: 50px;
color: white;
text-align: center;
}
我的问题是:如何通过单击正文更新 var 文本并在每次打开叠加层时获取新的随机字符串?到目前为止,var 文本中的字符串仅在我重新加载整个页面时更新。
感谢:)
使用 JSON 在页面中打印 PHP 数组:
<!-- language: lang-php -->
<?php
$info = array(
"cat",
"dog",
"bear"
);
?>
<!-- language: lang-js -->
<script type="text/javascript">
// (it's better to retrieve it in ajax)
var arr = <?php echo json_encode($info); ?>;
// 2. Roll some dice in Javascript
// Math.random returns a random value between 0 and 1
var text = "";
// wrapped in a function so you can pick new random values
function pickRandom() {
// Math.random returns a decimal number, and you need to access arrays using their indexes (0, 1, 2) not decimal numbers. Number.parseInt does the rounding.
text = arr[ Number.parseInt( Math.random()*arr.length ) ];
alert("new random value is: " + text);
}
pickRandom();
</script>
然后,代码的其余部分应该可以工作。希望这有帮助。
医生:
- JSON 编码:http://php.net/manual/fr/function.json-encode.php
- JS随机性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
你不能,
因为PHP是在服务器端执行的。
当您加载页面时,它会将最终的 HTML 发送到您的浏览器,结果为 <?php echo $info[array_rand ($info)];?>
.
如果安全性不是问题(游戏,银行业务...),您可以使用JavaScript使用随机性。
否则,您可以手动重新加载页面,如下所示:
$('#overlay').click(function() {
// reload the page silently. see also http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
window.location.href = window.location.href;
//$(this).remove();
});
相关文章:
- React:使用索引变量更新嵌套集合
- 范围变量更新,但不更新视图
- 正在将代码库中的C#变量更新到asp.net
- 使用变量更新剑道图表系列的数据会导致重绘将列从图表上绘制出来
- MongoDB 用变量更新数组
- 将变量更新为函数中的参数
- Javascript-变量更新
- 使用Javascript和PHP变量更新页面上的数据
- Angular js 在
标签上的变量更新$scope动画
- 如何通过参数变量更新对象的属性值
- 如何在范围变量更新时更新模板
- 简单的变量更新和写入页
- 函数在变量更新后的某个时间点执行
- javascript OO如何用一些JSON变量更新self参数
- 使用$set中的变量更新mongodb的node.js
- 将声明的null变量更新为布尔值
- 在查询部分使用变量更新查询
- 如何在回调中使用变量更新文档?
- 通过AJAX用PHP变量更新URL
- 防止在没有javascript的情况下在页面刷新后进行变量更新