一些信息
我正在开发一个可以在多个布局上加载数据的网页,这样用户就可以选择哪一个是最好的。它可以加载在列表或类似卡片的界面中,并且使用ajax加载数据
在这个页面中,我还为用户收到的新消息提供了一个通知程序。ajax函数是新的,当php脚本加载页面时,js脚本(在菜单项上的链接中添加一个带有未读消息数的徽章(工作正常。
我使用的是HTML5、PHP和jQuery以及mySQL数据库
jQuery使用
导入HTML
<script src=";https://code.jquery.com/jquery.js"gt<脚本>
所以这是最近的版本。
问题
现在,当我使用ajax将数据加载到页面上时,js脚本将不再工作。我在使用另一个js脚本时遇到了同样的问题,并通过使用委托事件绑定器解决了这个问题
但我的未读消息更新程序使用按时间间隔运行
<body onload="setInterval('unread()', 1000)">
read((js非常简单:
function unread() {
$(document).ready(function(){
$('#menu_item').load('ajax_countNewMsgs.php');
});
}
它调用一个php脚本,该脚本从DB中获取未读的msgs计数,并回显到jQuery将指向的元素中。希望我说得清楚
问题是,我不知道如何使用委托调用定时事件。没有太多希望,我尝试了
$(document).on('ready()','#menu_item', function () {
$(this).load('ajax_countNewMsgs.php');
});
那没用。
我读过很多关于js在DOM更改后停止工作的帖子,但我再次找不到解决这个问题的方法,也没有发现类似的问题。如有任何帮助或提示,我们将不胜感激。
编辑以更改第二个php脚本的名称
第二版-试图让事情变得更清楚
我尝试了@carter建议的
$(document).ready(function(){
function unread(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
$('#menu_item').html(response);
},
error: function(response){
//no error handling at this time
}
});
}
setInterval(unread(), 1000);
});
ajax_countNewMsgs.php脚本连接到DB,获取未读消息,并回显未读消息的数量。如果我尝试将ajax响应应用于另一个元素,比如<身体>结果正如预期的那样:每隔1秒,body html就会发生变化。因此,该功能正在发挥作用。正如我所说,我的JS都没有更改#menu_item。实际上,这个元素是另一个php scritp(menu.php(的一部分,它被导入到页面顶部。页面结构是这样的:
<html>
<head>
some tags here
</head>
<body>
<?php include (php/menu.html); ?>this will include menu with the #menu_item element here
<div id='wrapper'>
<div id='data'>
here goes the data displayed in two ways (card and list like). Itens outside div wrapper are not being changed.
</div>
</div>
</body>
</html>
即使元素没有被重写,js也找不到它来更新它的值。这不是完整的代码,但我想你可以看到正在做什么。
$(document).on('ready()','#menu_item', function () {
是无效的事件侦听器。如果你想知道DOM什么时候准备好了,你应该这样做:
$(document).ready(function () {
然而,我认为这并不是你真正想要的。函数unread
将重复激发,但每次都会附加一个事件侦听器。相反,如果你想在初始页面加载后每隔几秒钟进行一次ajax调用,你应该这样做(dataType属性可以是html、json等,选择你的毒药(:
$(document).ready(function(){
function makeCall(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
//handle your response
},
error: function(response){
//handle your error
}
});
}
setInterval(makeCall, 1000);
});
删除unread
函数上的内容:
$(document).ready(function(){
为什么
文档已经"就绪",并且此文档状态将仅触发1x-之后将永远不会调用"就绪状态"。使用以下语法:
jQuery(function($){