通过ajax加载内容

时间:2012-12-08 07:04:13

标签: javascript jquery ajax

我已经创建了这个用于加载数据的ajax脚本。

$("#submit").click(function(e){
    e.preventDefault()  
    var loading = "<img src='/images/loading.gif' alt='Loading...' />";
    var scrolltop=$('#scrollbox').attr('scrollTop');
    var scrollheight=$('#scrollbox').attr('scrollHeight');
    var windowheight=$('#scrollbox').attr('clientHeight');
//  var post = $(this).attr("name") + "=" + $(this).val();
    var form_data = $('#search_form').serialize();// + "&" + post ;

    var scrolloffset=20;
    $('#search').html(loading);
    $.post("dosearch.php",form_data,function(newitems) {
        $('#content').append(newitems);
            });
        if(scrolltop>=(scrollheight-(windowheight+scrolloffset))){
            $.post("dosearch.php",form_data,function(newitems) {
        $('#content').append(newitems);
            });
        }     
        });
});

此脚本将获取表单数据并对其进行序列化并将其发布到dosearch.php,之后dosearch将发布我们搜索限制的数据0,6。当滚动到达结果的div的底部我想要获取更多的内容,因此我创建了这个函数,它将再次获取我们的表单数据和我的结果div中的div数...然后使用这个div结果以防万一到限制$ number,6。

function scroll_result(form_data){
    var loading = "<img src='/images/loading.gif' alt='Loading...' />";
    var scrolltop=$('#scrollbox').attr('scrollTop');
    var scrollheight=$('#scrollbox').attr('scrollHeight');
    var windowheight=$('#scrollbox').attr('clientHeight');
    var scrolloffset=20;
    var divnumber = $('#content').children().size();
    var form_data = form_data + "&size=" + divnumber;

    if(scrolltop>=(scrollheight-(windowheight+scrolloffset)))
    {
        //fetch new items
        $.post('dosearch.php', form_data, function(newitems){
        $('#content').append(newitems);
        });
    }
    setTimeout('scroll_result(form_data)', 1500);
}

这个功能不起作用,我需要一些帮助

提前感谢...

1 个答案:

答案 0 :(得分:1)

我在这里设置了一个示例滚动侦听应用程序:

http://jsfiddle.net/E2wj2/2/

您需要收听scrollbox

的滚动事件
$('#scrollbox').scroll(function(){
  console.log('scrolling');
  scrolltop=$('#scrollbox').attr('scrollTop');
  if(scrolltop>=(scrollheight-(windowheight+scrolloffset))) {
    //do whatever you wish to do
  }
});

希望这有帮助。