从 html 按钮调用 php 函数而不刷新页面


Calling php function from html button without page refresh

我有一个php脚本:

<?php
$species = $_GET['species']
...//do things to prepare the query
$result = //result of the query.
if (isset($_GET['download'])){
    getCSV();
}
function getCSV(){
    if ($result->num_rows > 0){         
        $f = fopen("csvFile", "w");
        while ($row = $result->fetch_assoc()){
            fputcsv($f, $row);
        }
        fclose($f);
        echo ("downloaded");
    }
    else{
        echo ("no results to download");
    }
}
?>

还有一些 html 代码:

<button type="button" onclick="window.location.href='query.php?download=true'"> Click to download as csv file </button>

php 脚本和 html 代码都存在于同一个文件,query.php 中。php脚本也是从另一个地方调用的,它会向它发送"物种"GET请求(以及其他几个,但我懒得在这里包含它们)

我想在单击按钮时调用 getCSV 函数。我不希望页面刷新,所以我知道无论如何我都应该使用 ajax 和 jquery(并且我知道之前有很多关于为此目的使用 ajax 的问题)。但是,php 脚本需要将$_GET['species']和其他数据传递给它,因此当我单击按钮时(同样,如果我使用 ajax),"species"GET 变量会丢失,因为其他 GET 变量不会通过按钮传递给查询.php。因此,查询填充错误,并且对无用的数据调用 getCSV 函数。

getCSV() 函数是从 query.php 调用的。在调用时,我可以访问页面的 url,并对其进行操作以确定除了"下载"(例如"物种")之外的其他 GET 变量是什么。是否可以在不这样做的情况下调用该函数,因为我有很多变量?

索引.php请看这里

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<button type="button" id="test"> Click to download as csv file </button>
<input type="hidden" id="val" value="true"> <!--download filename value true and false-->
<script>
    $(function(){
        $('#test').click(function(){
            var val = $("#val").val();
            $.ajax({
                url: 'query.php',
                type: 'GET', // get method
                data: 'download='+val, // download get name + value go
                  success: function(data) {
                    // success
                    alert(data);
                  },
                  error: function(data) {
                    // error
                    alert(data);
                  }
            });
        });
    });
</script>

查询.php请参阅此处

<?php
$species = clean($_GET['download']); // clean func magic quotes fix
 if (empty($species)) {
     echo 'get name not empty';
        //  empty get name print
 }else{
    if ($species == 'true'){
        echo 'download';
        // true query code here...
    }else{
        echo 'no download';
        // error code here
    }
 }
?>

现场提供的文章样本的标题。在编写搜索之前。

我简单地告诉他,你可以调整你的系统。

问候。