首先单击失败,第二次单击在Ajax调用上成功•JQuery / PHP

时间:2013-10-17 18:35:06

标签: javascript php jquery

我有一个Ajax调用,它发布到PHP,完成后重新加载div

按钮(Ajax触发器)

<div class='btn btn-danger pull-right group-action' data-action='handle=" . $folder_name . "&action=delete_group' style=' margin:5px 10px 5px 5px;'>
    <i class='glyphicon glyphicon-remove'></i>
    <span> Delete Group</span>
</div>

Jquery的

<script type="text/javascript">

    $(document).on('click', '.group-action', function(){

        var action = $(this).attr('data-action');
        var randnum = Math.floor(Math.random()*1001);


        $.ajax({
            type: "POST",
            url: "server/php/delete_action.php",
            cache: false,
            data: action + "&random=" + randnum,
            success: function(){
                $('#show_groups').load('server/php/show_groups.php');
            }

        }); 

    });

</script>

PHP页面(delete_action.php)

<?php

    $dir_base = 'files/';

    $handle = $dir_base . $_POST['handle'];
    $action = $_POST['action'];

    function delete_all_images($dirname) {
        foreach(glob($dirname.'/*.*') as $v){
        unlink($v);
        }
    }

    function delete_group($dirname) {
       if (is_dir($dirname))
          $dir_handle = opendir($dirname);
       if (!$dir_handle)
          return false;
       while($file = readdir($dir_handle)) {
          if ($file != "." && $file != "..") {
             if (!is_dir($dirname."/".$file))
                unlink($dirname."/".$file);
             else
                delete_group($dirname.'/'.$file);    
          }
       }
       closedir($dir_handle);
       rmdir($dirname);
       return true;
    }

    if( (isset($action)) && (!empty($action)) && (isset($handle)) && (!empty($handle)) ){
        $doit = $action($handle);
        eval($doit);
    }

?>

当我在触发按钮上单击一次时,PHP的操作会执行应有的操作,但成功时的加载功能不会触发,但如果我再次单击该按钮,则它可以正常工作并且成功函数运行。

1 个答案:

答案 0 :(得分:1)

您是否曾尝试在ajax函数上使用async:false,

  $.ajax({
            type: "POST",
            url: "server/php/delete_action.php",
            cache: false,
            data: action + "&random=" + randnum,
            success: function(){
                $('#show_groups').load('server/php/show_groups.php');
            },
            async: "false",

        }); 

谢谢, Naumche