doukengzi3517 2019-05-16 09:01
浏览 108
已采纳

在html按钮中调用javascript函数时出错[复制]

This question already has an answer here:

I'm trying to call a JavaScript function on a button in html. Both the button and the JavaScript function are in the same file, however I am having an error saying that the function is not available.

function countFiles() {
  $directory = "/uploadFiles";
  $filecount = 0;
  $files = glob($directory.
    "*");
  if ($files) {
    $filecount = count($files);
  }

  if ($filecount > 0) {
    echo '<script type="text/javascript">',
      'window.location.href = "decrypt.php";',
      '</script>';
  } else {
    echo "<script type='text/javascript'>alert('Precisa de inserir pelo menos 1 ficheiro');</script>";
  }
}
<button onclick="countFiles()">Desencriptar</button>

</div>
  • 写回答

2条回答 默认 最新

  • dongwen1935 2019-05-16 09:23
    关注

    From your comment,

    I want call a function in html button. This function counts the number of files that a directory has. If number of files > 1 the page is redirect.

    You can achieve this with an asynchronous call to PHP - through AJAX.

    Method 1: Asynchronous call

    <script>
    function countFiles() {
      $.ajax({
        url: "getFileCount.php", 
        success: function(result) {
            if (result.count > 0) {
                window.location.href = "decrypt.php";
            } else {
                alert('Precisa de inserir pelo menos 1 ficheiro');
            }
        }}
    );
    </script>
    

    Then, create a file called getFileCount.php

    header('Content-Type: application/json');
    $directory = "/uploadFiles";
    $filecount = 0;
    $files = glob($directory . "*");
    
    if ($files){
         $filecount = count($files);
    }
    echo json_encode(['count' => $filecount]);
    

    Method 2

    However, if you don't expect the number of files to be changed between the page load and the click of the button, you don't need AJAX,

    <?php 
    $directory = "/uploadFiles";
    $filecount = 0;
    $files = glob($directory . "*");
    if ($files){
        $filecount = count($files);
    }
    ?>
    
    <script>
    function countFiles() {
        var fileCount = <?php echo $filecount; ?>;
        if(filecount > 0){
           window.location.href = "decrypt.php";
        }else{
            alert('Precisa de inserir pelo menos 1 ficheiro');
        }
    }   
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真