运行php脚本后没有Ajax成功

时间:2015-06-14 20:15:47

标签: php jquery ajax

我有一个php脚本,它执行我网站的数据库备份。可以通过单击网站管理面板上的按钮来触发此备份脚本。

我想在管理面板中有一些文字告诉用户备份何时进行以及何时完成(过程大约需要1分钟)。

我相信使用Ajax是这样做的唯一合理方式,到目前为止我已尝试过以下方法:

<button id="btn">Backup</button>
<script>
    $("document").ready(function(){
        $("#btn").click(function(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "backup/db_backup.php",
                success: function(data) {
                    alert("success!!!");
                }
            });
        });
    });
</script>

上面确实运行了备份脚本,但我不确定为什么一旦脚本运行完毕就不会触发警报。我需要在php文件中使用哪些特定内容才能使用它?

非常感谢任何帮助!

编辑:按要求添加了php脚本

<?php
    include_once '../includes/db_connect.php';

    ini_set("max_execution_time", 0);

    $zip = new ZipArchive();
    $dir = "backups";

    if(!(file_exists($dir))) {
        mkdir($dir, 0777);
    }

    $p = backup_tables($mysqli);
    echo $p;
    if (glob("*.sql") != false) {
        $filecount = count(glob("*.sql"));
        $arr_file = glob("*.sql");

        for($j=0;$j<$filecount;$j++) {
            $res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
            if ($res === TRUE) {
                $zip->addFile($arr_file[$j]);
                $zip->close();
                unlink($arr_file[$j]);
            }
        }
    }

    //get the current folder name-start
    $path = dirname($_SERVER['PHP_SELF']);
    $position = strrpos($path,'/') + 1;
    $folder_name = substr($path,$position);
    //get the current folder name-end

    $zipname = date('Y/m/d');
    $str = "dRbot-".$zipname.".zip";
    $str = str_replace("/", "-", $str);

    // open archive
    if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE) {
        die ("Could not open archive");
    }

    $zip->addFile(realpath($folder_name . "/" . $p));
    // close and save archive
    $zip->close();
    echo "Archive created successfully.";

    copy("$p.zip", "$dir/$str");
    unlink("$p.zip");

    /* backup the db OR just a table */
    function backup_tables($mysqli, $tables = '*') {
        //get all of the tables
        if($tables == '*') {
            $tables = array();
            $result = $mysqli->query('SHOW TABLES');
            while($row = $result->fetch_array(MYSQLI_NUM)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }
        $return = "";

        //cycle through
        foreach($tables as $table) {
            $result = $mysqli->query('SELECT * FROM '.$table);
            $num_fields = mysqli_field_count($mysqli);
            $return.= 'DROP TABLE '.$table.';';
            $result2 = $mysqli->query('SHOW CREATE TABLE '.$table);
            $row2 = $result2->fetch_row();
            $return.= "nn".$row2[1].";nn";

            while($row = mysqli_fetch_row($result)) {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++) {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = preg_replace("#n#","n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");n";
            }
            $return.="nnn";
        }

        //save file
        $path = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
        $handle = fopen($path,'w+');
        fwrite($handle,$return);
        fclose($handle);
        return $path;
    }

?>

2 个答案:

答案 0 :(得分:1)

你的脚本db_backup.php应输出JSON格式的东西,回复类似这样的东西。

echo json_encode(array('success'));

OR

您可以将代码更改为:

<button id="btn">Backup</button>
<script>
    $("document").ready(function(){
        $("#btn").click(function(){
            $.ajax({
                type: "POST",
                url: "backup/db_backup.php",
                success: function(data) {
                    alert("success!!!");
                }
            });
        });
    });
</script>

答案 1 :(得分:0)

我会尝试这样的事情:

data = Santa.Lucia

那应该给你你想要的东西。要记住的一件事是从服务器代码返回的内容。如果您要返回 var serverCall=function(){ var ajax=$.ajax({ type: "POST", dataType: "json", url: "backup/db_backup" }); return ajax.then(function(data,status,xhr){ // success }, function(){ // fail }); } $("#btn").on('click',serverCall); false,则对调用哪个回调处理程序没有影响。您需要在响应标头中发送true。这是jQuery确定请求是否成功的唯一方法。

最后。你只有一个成功的回调。除非服务器端返回HTTP status code4xx响应代码,否则您的代码仍然有效。然后它将触发您没有的失败回调处理程序,因此不会发生任何事情。您可以附加函数而不是名为5xx的{​​{1}}作为回调处理程序。无论结果如何,都会触发回调。

我建议调查我在jQuery文档中所说的内容。