所以我对AJAX有点新意,我试图让它发挥作用。我要做的是创建一个每隔3秒自动更新的消息应用程序。
这是我的剧本:
function first() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').html(output);
});
}
function searchm() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').val(output);
});
}
setInterval( "searchm()", 3000 );
这是我的messageSearch.php:
<?php
session_start();
$userdb = new mysqli('localhost', 'test', '', 'social-network');
if(isset($_POST['userVal'])) {
$searchm = $_POST['userVal'];
$output = '';
if ($searchm == ''){
echo $output;
exit();
}
$uidquery = mysqli_query($userdb, "SELECT * FROM users WHERE username='$searchm' LIMIT 1");
$uid= '';
while($row2 = mysqli_fetch_array($uidquery)) {
$uid = $row2['id'];
}
$uid = 2;
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'You have no messages.';
} else {
while($row = mysqli_fetch_array($query)) {
$from = $row['p1'];
$message = $row['message'];
$time = $row['time'];
$time = date('Y-m-d H:i:s', strtotime($time));
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
while($row1 = mysqli_fetch_array($fromResult)) {
$fromFirst = $row1['first_name'];
$fromLast = $row1['last_name'];
$from = $fromFirst.' '.$fromLast;
}
$output .= '
<li>
<a href="#">
<div>
<strong>'.$fromFirst.' '.$fromLast.'</strong>
<span class="pull-right text-muted">
<em>'.$time.'</em>
</span>
</div>
<div>'.$message.'</div>
</a>
</li>
<li class="divider"></li>
';
}
$output .= '<li><a class="text-center" href="#"><strong>See All Messages</strong> <i class="fa fa-angle-right"></i></a></li>';
}
}
echo ($output);
?>
由于某种原因,第一次加载工作正常,但第二次加载空白。希望你能提供帮助,但事先要感谢。
答案 0 :(得分:0)
setInterval( "searchm()", 3000 );
应该是
setInterval( searchm, 3000 );
PHP中的另一个错误:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3")
应该是:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=".$uid." AND `read`='n' LIMIT 3")
最后
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
到
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = ".$from);