【问题标题】:Jquery: Get the functions from a php fileJquery:从 php 文件中获取函数
【发布时间】:2021-10-09 20:14:51
【问题描述】:

我是 jquery 和 php 的新手。我有一个html页面,需要通过jquery在一个php文件中使用一些函数,然后用html打印结果。

我要做的是计算 3 个不同目录中的文件数,然后在 3 个不同的 div 中打印它们的结果。当我在 php 文件中只编写一个函数,并在 jquery 中通过load 调用它时,它工作正常。但我不知道如何在同一个 php 文件中将此方法用于 3 个不同的函数。你能帮帮我吗?

HTML:

<div class="result1"></div>
<div class="result2"></div>
<div class="result3"></div>
<script>window.onload = stats()</script>

JS:

function stats() {
$('.result1').load("counter.php"); //I don't know what to add here to get the result of only the function a1 in counter.php
$('.result2').load("counter.php"); //and for a2
$('.result3').load("counter.php"); //and for a3
}

PHP:

<?php

function a1() {
$i = 0;
$dir = '../folder1/';
if ($handle = opendir($dir)) {while (($file = readdir($handle)) !== false){if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++;}}
echo "$i";
}

function a2() {
$i = 0;
$dir = '../folder2/';
if ($handle = opendir($dir)) {while (($file = readdir($handle)) !== false){if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++;}}
echo "$i";
}

function a3() {
$i = 0;
$dir = '../folder3/';
if ($handle = opendir($dir)) {while (($file = readdir($handle)) !== false){if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++;}}
echo "$i";
}

?>

【问题讨论】:

    标签: javascript php html jquery


    【解决方案1】:

    添加指示要调用哪个函数的 URL 参数。然后在 PHP 中检查。

    JS:

    function stats() {
        $('.result1').load("counter.php?action=a1");
        $('.result2').load("counter.php?action=a2");
        $('.result3').load("counter.php?action=a3");
    }
    

    PHP:

    <?php
    
    switch ($_GET['action']) {
    case 'a1':
        a1();
        break;
    case 'a2':
        a2();
        break;
    case 'a3':
        a3();
        break;
    }
    
    function a1() {
        $i = 0;
        $dir = '../folder1/';
        if ($handle = opendir($dir)) {while (($file = readdir($handle)) !== false){if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++;}}
        echo "$i";
    }
    
    function a2() {
        $i = 0;
        $dir = '../folder2/';
        if ($handle = opendir($dir)) {while (($file = readdir($handle)) !== false){if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++;}}
        echo "$i";
    }
    
    function a3() {
        $i = 0;
        $dir = '../folder3/';
        if ($handle = opendir($dir)) {while (($file = readdir($handle)) !== false){if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++;}}
        echo "$i";
    }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 2013-04-11
      • 2010-12-23
      • 1970-01-01
      相关资源
      最近更新 更多