1

I have a code that will prompt if i want to delete files in the directory. The problem arises when the page refreshes, it will just delete the files without the prompt selection. I want to not delete the files even when the page refresh.

<script language="javascript">
function checkMe() {
    if (confirm("Are you sure")) {
        alert("Clicked Ok");
        <?php                   
            $files = glob('d:/pics/*'); // get all file names
            foreach($files as $file){ // iterate files
            if(is_file($file))
            unlink($file); // delete file
            }
        ?>
        return true;
    } else {
        alert("Clicked Cancel");
        return false;
    }
}
</script>

Here's the code for calling the function

<a href='index.php?main=add-doc' class='footer-img' onclick=\"return checkMe();\"><div class='record'><img src='images/download.png' style='position: relative; margin: auto;'/>Upload Record</div></a>
4

1 回答 1

5

你不能像那样从 javascript 调用 php,php 将始终执行。你想要的是 Ajax。

文件.php

$files = glob('d:/pics/*'); // get all file names

foreach($files as $file){ // iterate files
    if(is_file($file))
        unlink($file); // delete file
}

和javascript中的ajax,如果你使用jQuery,它会像

function checkMe() {
    if (confirm("Are you sure")) {
        $.get('file.php', function() {
            //ignore
        });
    }
}

或者您可以将 php 放入 index.php 文件并检查:

if (isset($_GET['main']) && $_GET['main'] == 'add-doc') {
    $files = glob('d:/pics/*'); // get all file names

    foreach($files as $file){ // iterate files
        if(is_file($file))
            unlink($file); // delete file
    }
}

在javascript中只放确认代码:

function checkMe() {
    return confirm("Are you sure");
}

当您单击链接并确认返回 true 时,浏览器将跟随链接并执行 php 代码。

于 2013-06-24T08:06:09.300 回答