使用ajax延迟输出数据?

时间:2012-01-05 03:36:18

标签: jquery ajax function delay slidetoggle

我正在努力进行切换

div元素目前有一些信息,当用户点击链接时,它会向上滑动,并向下滑动并显示新信息。

我正在研究ajax,所以当用户点击链接时,显示的新信息来自另一个页面。

('a').toggle(function(){
    $('.content').slideUp("fast");  
    $.ajax({
        type: "GET",
        url: "URL",
        data: data,
        success: function(data){
                $('.element').delay("slow").slideDown("fast").html(data);
        }
    });
},function(){
    $('.element').slideUp("slow");
    $('.content').delay("slow").slideDown("slow");

});


<div class='content'>
old information
</div>
<div class='element'>
New information from another page, being shown through ajax
</div>

这就是我脚本的基础知识。现在,当我点击链接时,新信息会在旧信息向上滑动之前立即显示。

关于我应该怎么做的任何想法或想法?也许更好的方法来写这个?

另外,有没有办法删除.html(数据)?所以当我滑回原始文件夹时,它会消失吗?或者我只需要使用.hide()函数?也许.remove()?

谢谢!

1 个答案:

答案 0 :(得分:1)

听起来你可能想在幻灯片上使用回调。一旦完成滑动功能,它将运行回调函数。 所以像这样:

$('a').toggle(function(){
    $('.content').slideUp("fast", function(){
        $.ajax({
            type: "GET",
            url: "URL",
            data: data,
            success: function(data){
                $('.element').delay("slow").slideDown("fast").html(data);
            }
        });
    });

虽然缺点是它不会在幻灯片发生之前通过AJAX加载结果,这有可能让你等待一段时间,但是,这听起来不像是在等待问题,所以这可能就是你所需要的一切。

如果我遇到同样的问题,听起来你正在遇到,我可能会创建2个变量,一个用于保持滑动状态,另一个用于保存从AJAX返回的HTML。 然后,我将使ajax成功回调和滑动回调运行一个函数,该函数将插入HTML并在满足2个条件时向下滑动:1)完成幻灯片并且2)AJAX请求返回结果。

这样,请求和slideup / slidingown都将尽可能快地协同工作,但不会重叠。

// here's an example of the function you would have both slideUp and ajax success callbacks run
var $html,
    $slide = false; // false indicates we're not in the process of a slideup

function process_data()
{
    // only process the slidedown if we're not in the process of a slideup and we have the html we're after
    if (!$slide && $html)
    {
        $('.element').slideDown('fast').html($html);
        // make sure to empty $html afterwards so we don't assume we have data next time this runs
        $html = '';
    }
}

所以你的幻灯片将在回调中包含上述功能

$slide = true;
$('.content').slideUp('fast', function(){
     // the slideup is completed, so set the slide back to false
     $slide = false;

    // process data
     process_data();
});

你的ajax成功也会使用process_data

success: function(data){
    // store the returning data in the html variable
    $html = data;

    // process data
    process_data();