我不能为我的生活弄清楚这里发生了什么:
我有以下jquery / ajax代码
$(document).on('click', '.get_friend', function() {
var messenger = $(this).text();
var user = '<? echo $username; ?>';
$.ajax({
url: '/includes/messenger.php',
data: {messenger: messenger, user: user},
type: 'GET',
success:function(data){
$('#messages').html(data);
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
然后是我的php文件
require($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');
$user = $_GET['user'];
$messenger = $_GET['messenger'];
if (isset($_GET['messenger'])) {
$count1="0";
$stmt1 = $db->prepare("SELECT message, sender, receiver, id, time FROM messenger WHERE (receiver = :receiver AND sender= :sender)
OR (receiver = :sender AND sender=:receiver) ORDER BY time DESC");
$stmt1->bindParam(':receiver', $user);
$stmt1->bindParam(':sender', $messenger);
$stmt1->execute();
$friend_msg = $stmt1->fetchAll();
foreach ($friend_msg AS $friend_msg1) {
echo '1';
$test = (++$count1 % 2) ? "itemOut" : "itemIn";
$mesg .= '
<div class="'.$test.'">
<a href="#" class="image"><img src="img/users/olga.jpg" class="img-polaroid"/></a>
<div class="text">
<div class="info clearfix">
<span class="name">'.$friend_msg1['sender'].'</span>
<span class="date">'.$friend_msg1['time'].'</span>
</div>
'.$friend_msg1['message'].'
</div>
</div>
';
}
}
echo $count1;
echo $mesg;
echo $friend_msg;
echo $user;
echo $messenger;
回报如下:
$count1 returns 0;
$mesg returns nothing
$friend_msg returns 'array'
$user returns the variable user as sent from ajax
$messenger returns the variable messenger as sent from ajax
如果我直接使用?user = name&amp; messenger = name2访问该页面,$ mesg将完美返回。问题是相当具体的,ajax没有得到foreach返回的结果。