Javascript 动态加载时,如何从.txt文件中获取动态内容以显示在多个html页面中
我在服务器上有一个文本文件:“m_data.txt”,其中的运行总数为77(例如)。总数由写入.txt文件的push.php页面更新Javascript 动态加载时,如何从.txt文件中获取动态内容以显示在多个html页面中,javascript,html,jquery,Javascript,Html,Jquery,我在服务器上有一个文本文件:“m_data.txt”,其中的运行总数为77(例如)。总数由写入.txt文件的push.php页面更新 <!DOCTYPE html> <html> <head> <title></title> <meta name="generator" content="BBEdit 13.1" /> </head> <body>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="generator" content="BBEdit 13.1" />
</head>
<body>
<form action="" method="get">
<label for="number">RunningTotal:</label><br>
<input type="text" id="number" name="number" value="0"><br>
<input type="submit" id="submit" value="Submit">
<!-- <input type="button" id="submit" value="Submit" onclick="sendform();"/> -->
</form>
<?php if (isset($_GET["number"])) { ?>
<p> Picked Up <?php echo $_GET["number"]; ?>.</p>
<?php
$myfile = fopen("m_data.txt", "w") or die("Unable to open file!");
$txt = $_GET['number'];
fwrite($myfile, $txt);
fclose($myfile);
?>
<?php } ?>
</body>
</html>
当页面box1和box2单独显示时,此功能正常。无需按下刷新按钮。每当我编辑push.php页面时,数字就会自动更新
但问题是,我希望只有在append2.html中加载时,才会显示box1和box2两个页面
<!DOCTYPE html>
<html>
<head>
<title>Append2</title>
<script type="text/javascript" src="autoM_Update.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
body {
}
table, th {
table-layout: absolute;
background-color: #FFFFFF;
text-align: center;
width: 900px;
height: 40px;
border: 1px solid black;
}
.div1 {
margin:0 auto;
text-align: center;
line-height: 40px;
height: 40px;
width: 900px;
border: 1px solid black;
background-color: white;
}
div.relative {
position: relative;
width: 900px;
height: 250px;
text-align: center;
line-height: 250px;
margin: auto;
}
div.relative2 {
position: relative;
width: 900px;
height: 175px;
text-align: center;
line-height: 175px;
margin: auto;
}
</style>
</head>
<body>
<div ><button class="button1" onclick="getContent1();">Load Box1</button></div>
<br>
<div ><button class="button1" onclick="getContent2();">Load Box2</button></div>
<br>
<br>
<br>
<div class="div1" align="center">This is Today's Date</div>
<div class="relative" id="content1"></div>
<div class="relative2" id="content2"></div>
<br>
<br>
<br>
</body>
<script>
function getContent1() {
$('#content1').load("box1.html");
}
function getContent2() {
$('#content2').load("box2.html");
}
</script>
</html>
附录2
正文{
}
表,th{
表布局:绝对;
背景色:#FFFFFF;
文本对齐:居中;
宽度:900px;
高度:40px;
边框:1px纯黑;
}
.1分部{
保证金:0自动;
文本对齐:居中;
线高:40px;
高度:40px;
宽度:900px;
边框:1px纯黑;
背景色:白色;
}
亲戚{
位置:相对位置;
宽度:900px;
高度:250px;
文本对齐:居中;
线高:250px;
保证金:自动;
}
第2分部{
位置:相对位置;
宽度:900px;
高度:175px;
文本对齐:居中;
线高:175px;
保证金:自动;
}
装货箱1
装载箱2
这是今天的日期
函数getContent1(){
$('#content1').load(“box1.html”);
}
函数getContent2(){
$('#content2').load(“box2.html”);
}
动态加载框时,编号不再显示或更新。甚至只是点击刷新按钮来显示号码对我来说也不是一个解决方案。我需要这个号码在.txt文件更改时自动更新。如果在append2.html文件中加载.txt文件,如何使该文件更改沿链向下传播到box1和box2。如果您能给我提供任何帮助、见解和代码示例,我将不胜感激
这也是在.js文件中使用getXmlHttpRequestObject。Chrome正在传递一个信息。。。主线程上的同步XMLHttpRequest不推荐使用,因为它会对最终用户的体验产生有害影响。如果这在未来可能行不通,那么解决这个问题的替代方案是什么。感谢马克。 < P>而不是使用<代码> XMLHttpRequest < /代码>进行无限轮询。在这里,每个要包含的页面都打算每秒发送请求以检索相同的数据。您可能想考虑的另一种选择是使用<代码>事件源< /代码>连接,与
append2.html
)中包含两个框
页面-但是这样做是无效的,因为html页面只能有一个html
,HEAD
和BODY
部分,因此将整个网页包含在DIV元素中不是继续的方式-相反,明显的选择是使用加载其他页面的iframe
元素。在下面的演示中,这些iFrame静态加载box1、box2页面,但您可以动态加载这些页面
要模拟您的设置,需要5页:-
sse.php ~ the file that reads the textfile every N seconds and sends data back
push.php ~ form that allows user to update text file with new number
append2.html ~ two statically declared iframes, content populated using `postMessage`
box1.html, box2.html ~ identical pages that `listen` for messages from append2.html
sse.php
<?php
set_time_limit( 0 );
ini_set('auto_detect_line_endings', 1);
ini_set('max_execution_time', '0');
ob_end_clean();
$sleep=1; # send data every $sleep seconds
$evt='txtupdate'; # Event name used in Javascript
$file='m_data.txt'; # read this file for updated number
#utility method to send formatted data
function sse( $evtname='iss', $data=null, $retry=1000 ){
if( !is_null( $data ) ){
echo "event:".$evtname."\r\n";
echo "retry:".$retry."\r\n";
echo "data:" . json_encode( $data, JSON_FORCE_OBJECT );
echo "\r\n\r\n";
}
}
# headers... consider modifying `Allow-Origin` to increase security
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *' );
#infinite loop - read file and send data payload
while( true ){
if( connection_status() != CONNECTION_NORMAL or connection_aborted() ) break;
$payload=[
'count' => intval( file_get_contents( $file ) )
];
call_user_func( 'sse', $evt, $payload );
/* -- Send output -- */
if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
@flush();
sleep( $sleep );
$payload = null;
}
if( @ob_get_level() > 0 ) {
for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
@ob_end_clean();
}
?>
<?php
$file='m_data.txt'; # read & update this file ( same as referenced in SSE )
$autoupdate=true; # does the user need to manually update the number in the form?
$int=file_exists( $file ) ? intval( file_get_contents( $file ) ) : 0;
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
$json=[];
if( $_POST['action'] == 'update-file' ){
$number=intval( $_POST['number'] );
if( $autoupdate ) $number++;
file_put_contents( $file, $number );
$json=json_encode( array( 'number'=>$number ) );
}
exit( $json );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>push</title>
<script>
/*
send ajax request to server, update source textfile
and return the new count. Use the callback to update
the displayed number.
*/
document.addEventListener('DOMContentLoaded',(e)=>{
let form=document.forms.push;
let bttn=form.querySelector('[type="button"]');
bttn.addEventListener('click',()=>{
let fd=new FormData( form );
fd.append('action','update-file');
fetch( location.href, { method:'post',body:fd } )
.then( r=>{ return r.json() })
.then( json=>{
form.number.value=json.number;
})
});
})
</script>
</head>
<body>
<form name='push'>
<label>Number: <input type='number' name='number' value='<?=$int;?>' /></label>
<?php
if( $autoupdate ){
echo "
<p>You do NOT need to manually update this number - simply click the button to increment the counter by 1</p>";
}
?>
<input type='button' value='Update' />
</form>
</body>
</html>
push.php
<?php
set_time_limit( 0 );
ini_set('auto_detect_line_endings', 1);
ini_set('max_execution_time', '0');
ob_end_clean();
$sleep=1; # send data every $sleep seconds
$evt='txtupdate'; # Event name used in Javascript
$file='m_data.txt'; # read this file for updated number
#utility method to send formatted data
function sse( $evtname='iss', $data=null, $retry=1000 ){
if( !is_null( $data ) ){
echo "event:".$evtname."\r\n";
echo "retry:".$retry."\r\n";
echo "data:" . json_encode( $data, JSON_FORCE_OBJECT );
echo "\r\n\r\n";
}
}
# headers... consider modifying `Allow-Origin` to increase security
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *' );
#infinite loop - read file and send data payload
while( true ){
if( connection_status() != CONNECTION_NORMAL or connection_aborted() ) break;
$payload=[
'count' => intval( file_get_contents( $file ) )
];
call_user_func( 'sse', $evt, $payload );
/* -- Send output -- */
if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
@flush();
sleep( $sleep );
$payload = null;
}
if( @ob_get_level() > 0 ) {
for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
@ob_end_clean();
}
?>
<?php
$file='m_data.txt'; # read & update this file ( same as referenced in SSE )
$autoupdate=true; # does the user need to manually update the number in the form?
$int=file_exists( $file ) ? intval( file_get_contents( $file ) ) : 0;
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
$json=[];
if( $_POST['action'] == 'update-file' ){
$number=intval( $_POST['number'] );
if( $autoupdate ) $number++;
file_put_contents( $file, $number );
$json=json_encode( array( 'number'=>$number ) );
}
exit( $json );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>push</title>
<script>
/*
send ajax request to server, update source textfile
and return the new count. Use the callback to update
the displayed number.
*/
document.addEventListener('DOMContentLoaded',(e)=>{
let form=document.forms.push;
let bttn=form.querySelector('[type="button"]');
bttn.addEventListener('click',()=>{
let fd=new FormData( form );
fd.append('action','update-file');
fetch( location.href, { method:'post',body:fd } )
.then( r=>{ return r.json() })
.then( json=>{
form.number.value=json.number;
})
});
})
</script>
</head>
<body>
<form name='push'>
<label>Number: <input type='number' name='number' value='<?=$int;?>' /></label>
<?php
if( $autoupdate ){
echo "
<p>You do NOT need to manually update this number - simply click the button to increment the counter by 1</p>";
}
?>
<input type='button' value='Update' />
</form>
</body>
</html>
推
/*
向服务器发送ajax请求,更新源文本文件
并返回新的计数。使用回调函数进行更新
显示的号码。
*/
document.addEventListener('DOMContentLoaded',(e)=>{
让表单=document.forms.push;
让bttn=form.querySelector('[type=“button”]');
bttn.addEventListener('单击',()=>{
设fd=新表单数据(表单);
append('action','update-file');
获取(location.href,{method:'post',body:fd})
.then(r=>{return r.json()})
。然后(json=>{
form.number.value=json.number;
})
});
})
编号:
append2.html
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Display</title>
<style>
iframe{
width:30%;
margin:1rem;
border:5px dashed rgba(100,100,100,0.25);
border-radius:1rem;
background:whitesmoke;
padding:0;
}
</style>
<script>
let evtsource = new EventSource( 'sse.php', { withCredentials: false } );
evtsource.addEventListener( 'txtupdate', function(e){
if( !e.origin == window.location.origin ) return false;
let json=JSON.parse( e.data );
let b1=document.getElementById('b1').contentWindow;
let b2=document.getElementById('b2').contentWindow;
b1.postMessage( json.count );
b2.postMessage( json.count );
});
</script>
</head>
<body>
<!-- box 1 -->
<iframe id='b1' src='box1.html'></iframe>
<!-- box 2 -->
<iframe id='b2' src='box2.html'></iframe>
</body>
</html>
展示
iframe{
宽度:30%;
保证金:1rem;
边框:5px虚线rgba(100100,0.25);
边界半径:1em;
背景:白烟;
填充:0;
}
让evtsource=neweventsource('sse.php',{withCredentials:false});
evtsource.addEventListener('txtupdate',函数(e){
如果(!e.origin==window.location.origin)返回false;
让json=json.parse(e.data);
设b1=document.getElementById('b1').contentWindow;
设b2=document.getElementById('b2').contentWindow;
b1.postMessage(json.count);
b2.postMessage(json.count);
});
box1和box2
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Box 1||Box 2</title>
<script>
window.addEventListener( 'message', (e)=>{
if( e.origin == window.location.origin ){
document.getElementById('liveDataM').textContent=e.data;
}
});
</script>
</head>
<body>
<div id='liveDataM' class='relative anim my_textBold'></div>
</body>
</html>
方框1 | |方框2
window.addEventListener('message',(e)=>{
if(e.origin==window.location.origin){
document.getElementById('liveDataM')。textContent=e.data;
}
});
打开两个浏览器选项卡,一个是加载
push.php
,另一个是append2.html
,并更新文本文件以同时查看两个iFrame中反映的值。希望有帮助/Chrome不应该显示该警告,因为您有一个异步调用(xhr.open(“GET”,url,true);
)。实际上,cli上没有其他选择
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Box 1||Box 2</title>
<script>
window.addEventListener( 'message', (e)=>{
if( e.origin == window.location.origin ){
document.getElementById('liveDataM').textContent=e.data;
}
});
</script>
</head>
<body>
<div id='liveDataM' class='relative anim my_textBold'></div>
</body>
</html>