2016-12-28 180 views
0

我有兩個數組。 1是空的,其他有5個項目。我想數它們並顯示它。Ajax返回錯誤結果

我發送Ajax請求是這樣的:

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); 
         } 
     }); 
    } 

我count_trash_delete.php看起來像這樣

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'; 
    } 
} 

,當我得到響應兩者都5.我無法理解。

回答

1

你要求頁面做同樣的事情,所以它做同樣的事情。這就是問題的代碼:

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

不要緊什麼$_GET['action']是代碼,如果它的存在都將設置$action1,如果它不存在,你我會將$action設置爲2。既然你總是通過action,那麼頁面總是會做同樣的事情。

你可能要設置$action$_GET['action']

if(isset($_GET['action'])) { 
    $action = (int)$_GET['action']; 
}else{ 
    $action = /*...some appropriate default number...*/; 
} 
+0

喔..我不能相信的,我沒有看到。非常感謝 – MHH