【问题标题】:Nothing is returned when trying to test php function尝试测试 php 函数时没有返回任何内容
【发布时间】:2013-04-18 17:16:49
【问题描述】:

我正在尝试在我的浏览器中测试一个函数,但没有返回任何内容。我访问了链接http://localhost/myfunctions.php?runFunction=writeJSON
我的功能是:

function writeJSON()
{
    $myfile="testson.json";
    $fileout=fopen($myfile,'w') or die("Fatal: Can't open JSON file for writing");
    global $arrayForJSON;
    if(isset($arrayForJSON))
    {
        fwrite($fileout,json_encode($arrayForJSON));
        echo "done";
    }
    else echo "Error: could not write to JSON file";
    fclose($myfile);
}

我在哪里弄错了,测试功能的正确方法是什么,或者我做错了什么?

该函数似乎没有运行,因为没有显示“完成”或“错误:无法写入 JSON 文件”,也没有对我的文件进行任何更改。

【问题讨论】:

  • echoing 吗?
  • 好吧,看来该功能没有运行。如何从myfunctions.php 中调用函数?
  • 这个函数在哪里调用?
  • 这不是你调用 PHP 函数的方式。您需要在文件末尾添加类似 writeJSON() 的行。
  • 那我真的有问题了。有人告诉我,使用 runFunction=myFunction 在 URL 中传递它会执行我的函数。问题是我需要在其他地方单击按钮时运行代码

标签: php testing localhost


【解决方案1】:

如果你想通过 get 运行一个函数,你需要包含 get 的代码...

//This is the function
function writeJSON()
{
    $myfile="testson.json";
    $fileout=fopen($myfile,'w') or die("Fatal: Can't open JSON file for writing");
    global $arrayForJSON;
    if(isset($arrayForJSON))
    {
        fwrite($fileout,json_encode($arrayForJSON));
        echo "done";
    }
    else echo "Error: could not write to JSON file";
    fclose($myfile);
}


// This will only call the function if ?runFunction=writeJSON
//is on the end of the URL
if(!empty($_GET["runFunction"])){
    if($_GET["runFunction"] == "writeJSON"){
        writeJSON(); // This line is the actual call to the function
    }
}

当然,如果您希望每次访问页面时都运行它,只需添加

writeJSON();

【讨论】:

    【解决方案2】:

    好吧,你需要运行这个函数。在 url 中传递它不会做任何事情。

    <?
    function writeJSON()
    {
    $myfile="testson.json";
    $fileout=fopen($myfile,'w') or die("Fatal: Can't open JSON file for writing");
    global $arrayForJSON;
    if(isset($arrayForJSON))
    {
    fwrite($fileout,json_encode($arrayForJSON));
    echo "done";
    }
    else echo "Error: could not write to JSON file";
    fclose($myfile);
    }
    writeJSON();
    ?>
    

    【讨论】:

    • 那我真的有问题了。有人告诉我,使用 runFunction=myFunction 在 URL 中传递它会执行我的函数。问题是我需要在其他地方单击按钮时运行代码
    • 有一些框架可以做到这一点,但我不认为你正在使用一个。看看龙猫的回应。只有当你在 url 中设置了 runFunction 时,他才会解释如何做到这一点。
    • 我只是在我的 localhost 上使用 sublimetext 并在 firefox 和 chrome 上测试代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2020-09-09
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多