[英]how to correctly handle object XMLHttpRequest in javascript from PHP via refreshDiv
When it comes to Javascript i have no idea what I am doing just try and error method. 当涉及到Javascript时,我不知道我在做什么,只是尝试和错误方法。 Been trying to do my research on AJAX and Javascript with no luck so far so please point me in the right direction. 到目前为止,我一直在尝试着对AJAX和Javascript进行研究,因此请指出正确的方向。 Basically I need to refresh a DIV every lets say 5s with data generated from PHP => Database, ON first load of the page everything is fine as it gets data directly from PHP but when Javascript kicks inn all i get is [object XMLHttpRequest] in place of DIV content; 基本上,我需要用PHP =>数据库生成的数据每隔5s刷新一次DIV,在页面的首次加载时,一切都很好,因为它直接从PHP获取数据,但是当Javascript启动inn时,我得到的只是[object XMLHttpRequest] in DIV内容的位置;
HTML 的HTML
<script type="text/javascript"></script>
<script>
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.open('GET', 'http://www.mysite.com/getuserinfo.php', true);
request.send();
document.getElementById("usinfo").innerHTML=request;
}
</script>
</head>
<body>
<div id="page">
and then the DIV 然后是DIV
<div id="usinfo" class="wrap">
<?php include("getuserinfo.php"); ?>
</div>
And the PHP goes like this : PHP如下所示:
require_once('../mysqli_connect.php');
$userid = 1000042;
$us_credit = 0 ;
$us_prof_view = 0 ;
$us_new_msg = 0 ;
//Get $us_credit , $us_prof_view , $us_new_msg
$q="SELECT ac_ballance, prof_views, COUNT (msg_id) AS messages FROM user_details INNER JOIN com_msg ON us_name = msg_to WHERE user_id =".$userid." AND msg_new =1";
$r = mysqli_query($dbc,$q);
if(mysqli_num_rows($r)== 1) {
$us_data = mysqli_fetch_array($r,MYSQLI_ASSOC);
$us_credit = $us_data['ac_ballance'];
$us_prof_view = $us_data['prof_views'];
$us_new_msg = $us_data['messages'];
}
mysqli_free_result($r); #not needed
?>
<p class="whtxt">Your Credits :
<?php echo $us_credit ; ?>
Profile views :
<?php echo $us_prof_view ; ?>
<a class="whtxt" href="http://www.mysite.com/inbox">New Messages :
<?php echo $us_new_msg ; ?>
</a>
</p>
Thanks in advance 提前致谢
Change 更改
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
to 至
if (request.readyState == 4 && request.status == 200) {
document.getElementById("usinfo").innerHTML=request.responseText;
}
This if statement waits for a successful response back from the server and then executes. 该if语句等待服务器成功返回响应,然后执行。 In your case, it waits for the HTML to be received then inserts it into the div. 在您的情况下,它等待HTML接收,然后将其插入div。
What you are trying to do is wrong for two reasons: 您尝试做的事情是错误的,原因有两个:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.