[英]How to insert new data before old data rather than after
I perform the php script to show random data. 我执行php脚本以显示随机数据。 I use ajax get to get data from the php script and continue getting data from the php script every 1 seconds.
我使用ajax get从php脚本获取数据,并继续每1秒从php脚本获取数据。 I also perform removal of the last row if the count is more or eqaul to 4. HOwever, my output is backward.
如果计数大于或等于4,我还将执行最后一行的删除。但是,我的输出是向后的。 I want to append new data before old data.
我想在旧数据之前附加新数据。
php script 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 code 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>
I thought of using before or insertbefore to insert new data before the old data. 我想到了使用before或insertbefore在旧数据之前插入新数据。 I also used node to insert before.It does not work.
我也用过node来插入,这行不通。 Please help me.
请帮我。 thank you..
谢谢..
You have to use prepend() from jquery : 您必须使用jquery的prepend() :
function randomdata(val) {
$('#result').prepend(val);
}
EDIT 编辑
I noticed an other error : $('result div:last-child').remove();
我注意到另一个错误:
$('result div:last-child').remove();
should be $('#result div:last-child').remove();
应该是
$('#result div:last-child').remove();
That's probably why it don't change, when it's at 4 divs it doesn't delete and redo the count, so you get stuck inside the while ... The fix from below should solve the problem 这可能就是为什么它不改变的原因,当它在4格时不会删除并重做计数,因此您陷入了困境……下面的修复应该可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.