2 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個(gè)贊
在基本形式中,您可以使用fetch
setInterval( ()=>{
fetch( '/path/to/php/script.php' )
.then( r=>{
return r.text();
})
.then( data=>{
alert( data );
})
.catch( err=>{
alert(err);
})
}, 1000 * 10 );// every 10s
如果您要使用如下實(shí)用函數(shù)來(lái)簡(jiǎn)化 DOM 節(jié)點(diǎn)的創(chuàng)建,您可以生成新內(nèi)容而無(wú)需最初嘗試擦除文檔。
來(lái)自 MDN:
注意:當(dāng) document.write 寫入文檔流時(shí),在關(guān)閉(加載)的文檔上調(diào)用 document.write 會(huì)自動(dòng)調(diào)用 document.open,這將清除文檔。
const create=function(t,a,p=null){
let el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
let _arr=['innerHTML','innerText','html','text'];
for( let x in a ) if( a.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, a[ x ] );
if( a.hasOwnProperty('innerHTML') || a.hasOwnProperty('html') ) el.innerHTML=a.innerHTML || a.html;
if( a.hasOwnProperty('innerText') || a.hasOwnProperty('text') ) el.innerText=a.innerText || a.text;
if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
return el;
};
然后你可以像這樣修改你的 ajax 函數(shù)(雖然未經(jīng)測(cè)試)
setInterval( ()=>{
fetch( 'chat-data.php' )
.then( r=>{
return r.text();
})
.then( data=>{
/*
Without seeing the HTML this is pseudo-code. Change to suit
your HTML structure.
*/
let parent=document.getElementById('TARGET_ELEMENT_ID');
let record=create(null,{},parent);
Object.keys( data ).map( key=>{
let obj=data[ key ];
create('span',{'class':'time-message','text':obj.when_send},record);
create('label',{'class':'nick-message','text':obj.sender},record);
create(null,{'text':obj.message},record);
create('hr',{},record);
})
})
.catch( err=>{
alert(err);
})
}, 1000 );

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
它每秒鐘都會(huì)給我數(shù)據(jù),但我無(wú)法在我的 div 中打印它...我嘗試使用 json_encode,所以我重新訪問(wèn)了我的腳本:
include("databaseCONNECTION.php");
$data = array();
foreach($dbConnection->query($sql) as $rows) {
array_push($data, array("when_send" => $rows['when_send'], "sender" => $rows['sender'], "message" => $rows['message']));
}
echo json_encode($data);
?>
// and this is my javascript script:
<script language="javascript">
setInterval( ()=>{
fetch( 'chat-data.php' )
.then( r=>{
return r.text();
})
.then( data=>{
for(i = 0; i < data.lenght; i++) {
document.write('<span class="time-message">', data[i]['when_send'], '- </span>');
document.write('<label class="nick-message"><strong>', data[i]['sender'], ': </strong></label>', data[i]['message'], '<br/><hr/>');
}
})
.catch( err=>{
alert(err);
})
}, 1000)
</script>
- 2 回答
- 0 關(guān)注
- 158 瀏覽
添加回答
舉報(bào)