Javascript jQuery AJAX检测滑动/向下运动中的数据更改显示
我想为新闻门户网站建立一个评论系统 我希望jqueryajax能够检测是否有人添加了注释数据,它会以slideDown动作自动更新添加的注释 我该怎么做?谢谢 注意:我使用ASP.NET作为服务器Javascript jQuery AJAX检测滑动/向下运动中的数据更改显示,javascript,asp.net,ajax,jquery,Javascript,Asp.net,Ajax,Jquery,我想为新闻门户网站建立一个评论系统 我希望jqueryajax能够检测是否有人添加了注释数据,它会以slideDown动作自动更新添加的注释 我该怎么做?谢谢 注意:我使用ASP.NET作为服务器 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: 'WebForm1.aspx',
success: function (data) {
$("#Urunler").html(data);
}
});
});
</script>
<style>
li
{
width: 100px;
height: 30px;
background: yellow;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul id="Urunler" runat="server">
</ul>
</div>
</form>
</body>
</html>
这是背后的代码
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Urunler.InnerHtml += "<li>" + dr.GetString(0) + "</li>";
}
}
cnn.Close();
}
}
}
}
你可以试试这个
var lastSearchedDate = new Date();
var isBusy = false;
function scrollEvent(e) {
var body = document.body,
html = document.documentElement;
var docHeight = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
var currentScroll = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
if (((docHeight * 75) / 100) < currentScroll) {
if (!isBusy) {
fetchData()
}
}
}
function fetchData(){
isBusy = true;
$.ajax({
cache: !1,
type: "POST",
data: $.toJSON(dataToPost_with_lastSearchedDate),
contentType: "application/json; charset=utf-8",
url: requestUrlToFetch_JSON_Data,
success: function (response_JSON_data) {
// Parse this JSON data and Append HTML to any div you want on Your Page
doStuff(response_JSON_data);
lastSearchedDate = new Date();
isBusy = false;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(ajaxOptions);
alert(thrownError);
alert(xhr.status);
}
});
}
function OnFirstLoad() {
fetchData();
if (document.attachEvent) {
document.attachEvent('onscroll', scrollEvent);
} else if (document.addEventListener) {
document.addEventListener('scroll', scrollEvent, false);
}
}
window.onload = OnFirstLoad;
请注意,我们使用的是javascript date,需要在服务器web/page方法中对其进行解析,我们已使用DateTime.ParseExact对其进行了请求。您需要将已加载的数据传递给服务器,服务器可以检查并返回尚未加载的数据。这里我还建议使用setTimeout而不是setInterval。因为setInterval总是在一个时间间隔后触发下一个调用,所以在函数中,您也使用ajax,这也是一个缺点=>当您的服务器负载很重且响应时间很慢时,这可能会变得混乱。在这个函数中,我们应该只在当前ajax完成时设置下一个间隔 需要更新服务器端代码以返回ID并检查ID
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Check for already loaded Ids, I assume that each record in your database has an Id
string loadedIds = Request.QueryString["loaded"];
string sql = "SELECT EmployeeId,FirstName FROM Employees";
if (!string.IsNullOrEmpty(loadedIds)){
sql = "SELECT EmployeeId ,FirstName FROM Employees WHERE EmployeeId NOT IN ("
+ loadedIds +")";
}// You could query it using a safer method than string concatenation, here I just demonstrate the idea
cnn.Open();
SqlCommand cmd = new SqlCommand(sql, cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//This should be a Literal Control, embed Id in the response.
Urunler.Text += string.Format("<li employeeId='{0}'>{1}</li>",dr.GetString(0),dr.GetString(1));
}
}
cnn.Close();
}
}
}
}
如果我没弄错的话,你正在寻找类似facebook/gmail的实时通知 您可以通过实现以下几种体系结构来实现: Ajax池:每隔5秒向服务器发出Ajax请求,服务器将向您提供最新的评论。这是最简单也是最重的方法。有了一点流量,就不会花太多时间让服务器上充斥着这么多不必要的请求,因为即使什么都没有发生,您也会执行请求。 Web套接字:您可以使用Socket.io并打开一个套接字将更新转发给所有客户端。这是解决此问题的常用方法。也很漂亮。您可以使用答案来应对这种方法。 反向Ajax/Comet:最后一个是最难的。Facebook使用这种架构,因为他们正在处理一些高流量:p我们可以假设这一个有能力扩展。您可以通过视频了解反向ajax或comet方法。这有助于你了解它。 更新:
这似乎给了你一点不同的技巧来实现你的目标。这可能会有帮助。试试这样的方法,我从未实现过,可能对您有用 这两种方法都是运行一个用PHP编写的服务器文件,等待连接。一旦连接到一个或多个客户端,数据就可以双向推送。有几个PHP WebSocket项目。看看这个: node.js=> BinaryJS=> 我要试一试 这应该每五秒钟从服务器获取一次LI,并将它们与任何现有注释进行比较,如果它们不同,则将新注释插入DOM并向下滑动:
var comments = {
get: function () {
return $.ajax({
url : 'WebForm1.aspx',
cache : false
});
},
check: function (coll1, coll2, UL_ID) {
var diff = [];
$.each(coll2, function (_, li2) {
var same = false;
$.each(coll1, function (_, li1) {
if ($(li1).text() == $(li2).text()) same = true;
});
if (!same) diff.push(li2);
});
this.output(diff, UL_ID);
},
poll: function (UL_ID) {
var self = this;
self.get().done(function (data) {
self.check($(UL_ID).find('li'), $('<ul />').append(data).find('li'), UL_ID);
});
},
output: function (elems, UL_ID) {
$.each(elems, function (i, elem) {
$(elem).hide().delay(i * 300).slideDown(350).appendTo($(UL_ID));
});
},
init: function (UL, interval) {
var self = this;
setInterval(function () {
self.poll(UL);
}, interval);
this.poll(UL);
}
}
$(document).ready(function () {
comments.init('#Urunler', 5000);
// ^^ starts plugin ^^ ID ^^ polling speed (5 seconds)
});
我强烈建议在数据库中为每个注释提供一个UUID,然后使用该UUID进行比较以找到新的注释。
上面的代码现在只比较注释的内容,因此如果完全相同的注释发布两次,可能会出现问题
看起来您的数据库输出的唯一内容就是注释本身,没有唯一标识符,因此如果您为UUID添加一行,则需要更改数据库结构,这在我看来有点超出了问题的范围
下面是一个快速演示,其中数据库已替换为本地存储
在此处检查服务器发送的html5事件,这是twitter和Facebook使用的。此checkcount中的用户setinterval方法使用setinterval检查将值存储在hiddenfield中,即已添加任何Commnet,如果已添加,则只需添加已添加的额外注释,并将其淡入幻灯片的位置?。这与我的问题无关,在我的问题中没有滚动事件。你确定他们使用它吗?你能分享来源吗?@HasanAlaca是的,看起来是这样:@HasanAlaca-哇,谢谢!我不明白为什么我没有得到任何更新投票,我花了相当长的时间才弄明白,但是所有的更新投票都指向了答案,建议了数据检索的一般解决方案,所以我认为当我发布了一些我认为有效的东西时,我误读了一些东西!另外,注意关于每个注释的唯一标识符的注释,这将使比较注释更容易,并且比仅仅检查注释的内容更灵活,并且与上面相同的功能基本上也可以工作,只需对其进行一些小的更改。
var comments = {
get: function () {
return $.ajax({
url : 'WebForm1.aspx',
cache : false
});
},
check: function (coll1, coll2, UL_ID) {
var diff = [];
$.each(coll2, function (_, li2) {
var same = false;
$.each(coll1, function (_, li1) {
if ($(li1).text() == $(li2).text()) same = true;
});
if (!same) diff.push(li2);
});
this.output(diff, UL_ID);
},
poll: function (UL_ID) {
var self = this;
self.get().done(function (data) {
self.check($(UL_ID).find('li'), $('<ul />').append(data).find('li'), UL_ID);
});
},
output: function (elems, UL_ID) {
$.each(elems, function (i, elem) {
$(elem).hide().delay(i * 300).slideDown(350).appendTo($(UL_ID));
});
},
init: function (UL, interval) {
var self = this;
setInterval(function () {
self.poll(UL);
}, interval);
this.poll(UL);
}
}
$(document).ready(function () {
comments.init('#Urunler', 5000);
// ^^ starts plugin ^^ ID ^^ polling speed (5 seconds)
});