我执行php脚本来显示随机数据。我使用ajax get从php脚本获取数据并继续每1秒从php脚本获取数据。如果计数更多或者eqaul为4,我也会删除最后一行.Howwever,我的输出是向后的。我想在旧数据之前附加新数据。
php脚本
<?php
$countryarr = array("UNITED STATES", "INDIA", "SINGAPORE","MALAYSIA","COLOMBIA","THAILAND","ALGERIA","ENGLAND","CANADA","CHINA", "SAUDI ARABIA");
$length = sizeof($countryarr)-1;
$random = rand(0,$length);
$random1 = rand(0,$length);
$random_srccountry = $countryarr[$random];
$random_dstcountry = $countryarr[$random1];
echo "<div>[X] NEW ATTACK: FROM [".$random_srccountry."] TO [".$random_dstcountry."] </div>";
?>
html代码
<html>
<head>
<title>Add new data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#result {
width: 500px;
height:500px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
var $auto_refresh = setInterval(function() {
var $count = $('#result div').length;
while ($count >= 4) {
$('result div:last-child').remove();
$count = $('#result div').length;
}
updateServer();
}, 1000);
//Remove last div if the count is more than 4
function updateServer() {
$.get({
url: 'randomData.php',
dataType: 'text',
success: randomdata
});
}
function randomdata(val) {
$('#result').append(val); //i want to insert before in other words new data appear at the top and old data remain down
}
</script>
</body>
</html>
我想过使用before或insertbefore在旧数据之前插入新数据。我之前也使用过节点插入。它不起作用。请帮我。谢谢..
答案 0 :(得分:0)
您必须使用jquery中的prepend():
function randomdata(val) {
$('#result').prepend(val);
}
修改强>
我注意到其他错误:$('result div:last-child').remove();
应为$('#result div:last-child').remove();
这可能就是为什么它不会改变,当它在4个div时它不会删除并重做计数,所以你会陷入困境......从下面修复应解决问题