php - php 中的 Ajax 找到正确的 div/类

标签 php javascript html css class

<div id = 'eventcontainer' >
<span id = 'class'>
<?php

//Getting posts from DB

$event1 = mysql_query("SELECT post,date,memid FROM postaction WHERE memid = '$id' ORDER           BY date DESC LIMIT 5;");

while ($row1 = mysql_fetch_array($event1))
{

$event = $row1['post'];
$timeposted = $row1['date'];

$eventmemdata = mysql_query("SELECT id,firstname FROM users WHERE id = '$id' LIMIT 1");

while($rowaa = mysql_fetch_array($eventmemdata))
{
$name = $rowaa['firstname'];
 $eventlist = "$event <br> $name";
}


echo " <div id = 'eventer'> $timeposted <br>$eventlist</div> <input name='myBtn'            type='submit' value='increment' onClick='javascript:ajax_post();'>
<input name='lol' type='submit' value='dec' onClick='javascript:ajax_posta();'>
<div id = 'status'>lol</div>";
echo "<br>";

}
$('.eventcontainer.button').click(function() { 
$.post('javas.php', function(data) {
   $(this).parent('div').find('.status').html(data);
})
});
?>
</div>
</span>

尝试运行此代码时出现错误。 我想做的是尝试读取单击按钮的 div/类,然后仅在该类中执行相关的 ajax/jquery 功能。

这是 Ajax/Jquery 函数 ajax_post(){

  $('.eventcontainer.button').click(function() { 
$.post('javas.php', function(data) {
   $(this).parent('div').find('.status').html(data);
})
});


hr.open("POST", url, true);

// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (++num)); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";

}

最佳答案

如评论所述,您的 PHP 标记中不应包含 jQuery。将一些脚本脚本标记添加到您的页面头部,添加一个 document.ready 处理程序,然后将脚本放在那里。

请注意,一旦您完成此操作,您仍然会遇到一些问题,因为您将 this 值弄混了。

$('.eventcontainer.button').click(function() { 
   $.post('javas.php', function(data) {
      $(this).parent('div').find('.status').html(data); 
   })
});

一旦您点击了 $.post 调用的回调,this 就不再等于您点击的元素。在调用 post 之前,您需要将该元素保存在局部变量中。

有点像

$('.eventcontainer.button').click(function() { 
    var self = this;
    $.post('javas.php', function(data) {
      $(self).parent('div').find('.status').html(data);
   })
});

关于php - php 中的 Ajax 找到正确的 div/类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8511645/

相关文章:

javascript - dc lineChart 单击时弹出数据点信息

javascript - div 显示自动生成的内联样式

php - Laravel 打包 html 到 pdf

php - ZF2 Zend\Db 使用 Mysql 表达式插入/更新(Zend\Db\Sql\Expression?)

php - PDO PHP 中的分页

javascript - mongodb中查询日期

php - 无法确认 SES 退回的 Amazon SNS 订阅

javascript - 表单操作期间后退按钮问题

html - 仅 CSS 下拉菜单

javascript - 仅使用 javascript、HTML 和 CSS 模拟用户登录