使用ajax延迟输出数据



我正在尝试切换

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()?

谢谢!

听起来您可能想在幻灯片上使用回调。一旦slideup函数完成,它将运行回调函数。这样的东西:

$('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加载结果,如果让你等待额外的时间,这是有可能的,然而,这听起来不像是在等待问题,所以这可能就是你所需要的。

如果我遇到了听起来像你遇到的同样的问题,我可能会创建两个变量,一个保存slideup状态,另一个保存从AJAX返回的HTML。然后,我会让ajax成功回调和slideup回调都运行一个函数,如果满足两个条件,该函数将插入HTML并向下滑动:1)slideup完成,2)ajax请求返回结果。

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

// 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();

最新更新