【问题标题】:How do I toggle content between tabs through ajax/php?如何通过 ajax/php 在选项卡之间切换内容?
【发布时间】:2016-03-09 03:40:22
【问题描述】:

我已将我的内容分为两个选项卡,并使用 javascript 在两个选项卡之间切换。

<div class='tab-container'>
<div class='tab-1'>
<?php 
$sql="SELECT * FROM posts WHERE status='tab1'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
<div class='tab-2'>
<?php
$sql="SELECT * FROM posts WHERE status='tab2'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
</div>   

Php 代码通过 WHERE 子句 select * from posts where status='tab1'; 在选项卡之间划分内容,以便从一个选项卡中删除帖子 ajax 下面给出的请求会触发 php 代码,该代码将内容状态从 tab1 更新到 tab2。

<script type="text/javascript">
$(function() {
$(".restore").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Restore?"))
  {
$.ajax({
type: "GET",
url: "restore.php",
data: info,
success: function(){ 
}
});
     $(this).parents(".db").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>

因此该帖子已从 tab1 中删除。这里的想法是通过 ajax 将帖子从一个选项卡移动到另一个选项卡。 javascript 在从一个选项卡中删除帖子方面效果很好,但是为了使该帖子出现在另一个选项卡中,我必须重新加载页面,因为我没有为此使用 ajax。所以问题是我不知道如何在不刷新页面的情况下通过 ajax 将该帖子动态添加到另一个选项卡。

【问题讨论】:

    标签: javascript php jquery ajax tabs


    【解决方案1】:

    要从 ajax 调用中获取内容,您必须在服务器端回显它。

    可能是这样的

    echo "hi, this is new content";
    

    现在 ajax 成功了

    success: function(data){  
         alert(data); this will alert what was echoed in php(hi, this is new content)
    }
    

    如果要将内容添加到视图中的某个 div,

    $("class or id for the div").html(data);
    

    【讨论】:

      【解决方案2】:

      在restore.php 中,您应该获取选定的帖子,然后将该帖子的状态更新为tab2。并将该结果附加到主 php 页面中。您可以通过 restore.php 附加相同的内容。

      【讨论】:

        【解决方案3】:

        试试这个

        HTML

        <div class="tabs" id="d-tab1"></div>
        <div class="tabs" id="d-tab2"></div>
        <a href="#" class="restore"  id="tab1">
        <a href="#" class="restore"  id="tab2"> 
        

        JS

        $('.restore').click(function(e){
            e.preventDefault();
            var $tab = $(this);
            $.post('restore.php',{id: $tab.attr('id')},function(html){
                $('.tabs').hide();
                $('#d-'+$tab.attr('id')).html(html).show();
            })
        })
        

        或使用 Jquery 选项卡https://jqueryui.com/tabs/

        【讨论】:

          【解决方案4】:

          同意@Niranjan N Raju。但是想补充一点。

          使用console.log(data) 代替alert(data),因为最后不显示对象信息。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-11-24
            • 1970-01-01
            • 2012-10-04
            • 2018-05-29
            • 2011-01-20
            • 2023-03-13
            相关资源
            最近更新 更多