doubo4824 2016-12-28 10:27
浏览 32
已采纳

Ajax返回错误的结果

I have two arrays. 1 is empty and other have 5 items. I want to count them and display it.

i send ajax request like this :

function countTrash()
    {
        $.ajax({
               type: "GET",
               url: "count_trash_delete.php",
               data: "action=1",
               success: function(response){
                          $("#badge3").html(response);
                        }
       });
    }




function countRemove()
    {
        $.ajax({
               type: "GET",
               url: "count_trash_delete.php",
               data: "action=2",
               success: function(response){
                          $("#badge2").html(response);
                        }
       });
    }

My count_trash_delete.php looks like this

if(isset($_GET['action'])) {
    $action = 1;
}else{
    $action = 2;
}

if($action === 1){

    $trash_arr = file_get_contents('trash_bots.json');
    $trash_arr = json_decode($trash_arr);
    $number_of_trashed = count($trash_arr);

    echo $number_of_trashed;

}elseif($action === 2){

    $remove_arr = file_get_contents('remove_bots.json');
    $remove_arr = json_decode($remove_arr);

    if(!empty($remove_arr)){        
    $number_of_removed = count($remove_arr);    
        echo $number_of_removed;        
    }else{
        echo 'Empty';
    }   
}

When i get response both are 5. Which i cant understand.

  • 写回答

1条回答 默认 最新

  • doukengzi3517 2016-12-28 10:30
    关注

    You're asking the page to do the same thing, so it does the same thing. This is the problem code:

    if(isset($_GET['action'])) {
        $action = 1;
    }else{
        $action = 2;
    }
    

    It doesn't matter what the value of $_GET['action'] is in that code, if it's there at all you'll set $action to 1 and if it isn't there you'll set $action to 2. Since you're always passing action, the page always does the same thing.

    You probably want to set $action to the value of $_GET['action']:

    if(isset($_GET['action'])) {
        $action = (int)$_GET['action'];
    }else{
        $action = /*...some appropriate default number...*/;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog