【问题标题】:if/else statement doesn't work after an AJAX requestif/else 语句在 AJAX 请求后不起作用
【发布时间】:2013-09-16 17:16:33
【问题描述】:

我目前正尝试在我的代码中为 like 按钮实现一点 AJAX。 我在屏幕上显示LikeDislike 按钮。我发出 AJAX 请求来检查我的数据库,并取决于结果。其中一个按钮应该隐藏。

这是我的脚本:

<script type="text/javascript">
    function check(){
        var urliditem = document.location.href;
        var splitted = urliditem.split('item=');
        var id = splitted[1];

        $.post(
            "ajax/likes.php",
            { id: id },
            function(check){
                alert(check);
                if (check == 1){
                    //show the Like button
                    $("#dislike").hide();
                }
                else if (check == 0){
                    //show the Dislike button
                    $("#like").hide();
                }
                else{
                    alert('An error has occured');
                }
            }
        );  
    }

    $(document).ready(function() {
        $("#test").click(function(e){
            e.preventDefault();
            check();
        });
    });
</script>

我检查我是否从我的 AJAX 请求中获得了结果,但 if/else 语句在调用后似乎不起作用。我不明白为什么。可能是 show()/hide() 函数不起作用。

有什么想法吗?我的脚本正确吗?

按钮

<?php
    echo '<div id="dislike" class="likes">'.$donneeitem['likes'].' ♥</div><a class="btn-primary btn pull-right" href="index.php?page=action&action=unlikeitem&id='.$_GET['item'].'">Unlike</a>';
    echo '<div id="like" class="likes">'.$donneeitem['likes'].' ♥</div><a class="btn-primary btn pull-right" href="index.php?page=action&action=likeitem&id='.$_GET['item'].'">Like</a>';
?>

ajax/likes.php

    $check = db_query('SELECT * FROM likes_item WHERE user_id = ? AND item_id = ?', array($_SESSION['mc']['id'], $item_id))->fetchColumn();
    if ($check>0) {
        echo 0; //To show the Dislike button
    }
    else {
        echo 1; //To show the Like button
    }

【问题讨论】:

  • check的返回值是多少?
  • 好吧,console.log(check) 的结果是一样的。你在哪里看到那个多余的引用? check的返回值为0或1
  • 我有一个 0,正如预期的那样
  • 好的,让我们反过来说:您是否显示了警报(带有“错误...”)?将console.log($('#like')) 添加到if (check == 0) 分支时会发生什么?
  • @raina77ow ah i c,好吧,string false false 早先通过我返回的兔子洞,但我会让你继续这个。我得回去工作了。大声笑

标签: jquery ajax hide show show-hide


【解决方案1】:

尝试如下更改您的脚本,这将隐藏您不想要的按钮,并显示相应的按钮,您编写的代码似乎只是隐藏按钮而不显示它。

function(check){
            alert(check);
            if (check == 1){
                //show the Like button
                $("#dislike").hide();
                $("#like").show();
            }
            else if (check == 0){
                //show the Dislike button
                $("#like").hide();
                $("#dislike").show();
            }
                else{
                    alert('An error has occured');
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2022-01-16
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多