从JQuery内部调用PHP函数file_put_contents

use*_*307 5 javascript php jquery

我在JQuery中有一个函数,当满足条件时调用PHP函数.一切顺利,直到我可以file_put_contents.似乎必须抛出JQuery不知道如何解释的某种输出.这是我的代码:

JQuery部分,其中$ downloader是类实例,finishedDownloading是一个javascript变量:

if (finishedDownloading==<?php echo $downloader->_totalFiles ?>){

    <?php $downloader->MergePDFs(); ?>

}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.这是我的PHP:

    function MergePDFs()
    {

        $combinedFiles = "";

        foreach ($this->_fileNamesArray as $filename) {
            $combinedFiles .= file_get_contents($filename); //these are the urls of my files
        }


        echo "document.getElementById('test-if-finished').innerHTML = 'Test output: " . $this->_file . "'"; // this is for testing

        //The above code works, the problem comes when I add the lines below

        file_put_contents("all-files.pdf",
                $combinedFiles);
Run Code Online (Sandbox Code Playgroud)

如果我评论file_put_contents行,一切顺利.

如果我取消注释,当我运行代码时,我得到一个疯狂的错误"未捕获的referenceError",说明我的JQuery函数没有定义.

有人能告诉我发生了什么事吗?

谢谢

编辑:我认为file_put_contents正在返回一些JQuery不知道该怎么做的值.

编辑2:这无法完成,即使我能够摆脱jquery错误,该函数在页面加载时执行,而不考虑if语句

Flo*_*ian 2

在 jQuery 部分中,您不应通过将 PHP 函数包含在 javascript 代码中来调用它们。在您的示例中,无论如何都会处理 PHP 代码,除非 jQuery 部分的 if 条件满足或不满足。

对 jQuery 尝试类似的操作:

if (finishedDownloading==<?php echo $downloader->_totalFiles ?>){
    $.get('mergepdf.php');
}
Run Code Online (Sandbox Code Playgroud)

和 mergepdf.php 就像你的代码一样:

<?php
function MergePDFs()
{

    $combinedFiles = "";

    foreach ($this->_fileNamesArray as $filename) {
        $combinedFiles .= file_get_contents($filename); //these are the urls of my files
    }


    echo "document.getElementById('test-if-finished').innerHTML = 'Test output: " . $this->_file . "'"; // this is for testing and works fine

    file_put_contents("all-files.pdf",
        $combinedFiles);
    ...
}

MergePDFs();
Run Code Online (Sandbox Code Playgroud)