javascript Ajax 代码自动刷新一个 php 文件并更新它的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20785257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax code the auto refresh a php file and updates it's vaules
提问by iSaumya
First I want admit that I have no knowledge in ajax. I'm building a small application, where I have a load.php file and within it, I have echoed 3 variables, i.e $loadout[0];
$loadout[1]; $loadout[2];
The PHP file is working fine and showing up the values.
Now I have another html page index.html which will actually users see. In this html file have 3 divs on the body
首先我要承认我对ajax一无所知。我正在构建一个小型应用程序,其中有一个 load.php 文件,在其中,我回显了 3 个变量,即$loadout[0];
$loadout[1]; $loadout[2];
PHP 文件工作正常并显示值。现在我有另一个 html 页面 index.html 它将实际用户看到。在这个 html 文件中,正文有 3 个 div
<div id="out1"></div>
<div id="out2"></div>
<div id="out3"></div>
Now I want you people to help me with the ajax code, which will keep reloading the load.php file of mine and keep updating the output values on the respective div. But index.html page will not reload. load.php will reload inside hiddenly in every 1 sec.
现在我希望你们帮助我处理 ajax 代码,这将不断重新加载我的 load.php 文件并不断更新相应 div 上的输出值。但是 index.html 页面不会重新加载。load.php 将在每 1 秒内隐藏地重新加载。
Please help. What will be the ajax code?
请帮忙。ajax 代码是什么?
回答by AyB
In your load.php at the end:
在你的 load.php 最后:
echo json_encode($loadout);
In index.html
在 index.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
//Calling function
repeatAjax();
function repeatAjax(){
jQuery.ajax({
type: "POST",
url: 'load.php',
dataType: 'json',
success: function(resp) {
jQuery('#out1').html(resp[0]);
jQuery('#out2').html(resp[1]);
jQuery('#out3').html(resp[2]);
},
complete: function() {
setTimeout(repeatAjax,1000); //After completion of request, time to redo it after a second
}
});
}
</script>