doutusheng5879 2013-02-12 13:58 采纳率: 0%
浏览 14
已采纳

如何在变量中包含来自不同文件的返回值

I can return a value from embedded php within the variable (as below), but in this case I would like to get the output of a php file e.g. result.php.

var jsVar = "<?php echo 'thisisfromphp' ?>";

So running 'result.php' would produce a result to be returned. How could I grab this result from result.php and use it as the variable - I was thinking something like:

var jsVar = "<?php echo result.php ?>";

P.S. I would embed the php code from result.php in the variable (as above) but it all gets to messy..

  • 写回答

1条回答 默认 最新

  • duanhuang4841 2013-02-12 14:01
    关注

    What you should do is refactor your code. Don't have result.php echo something out that you try and capture. That's not resuable code. Abstract whatever it does into a function that can be reused, then you can just require "result.php" and later callYourFunction() to get the desired output.

    If, however, you are insistent on doing it this way (which, again, I advise against), you could:

    ob_start();
    require_once 'result.php';
    $contents = ob_get_contents();
    ob_end_clean();
    
    // later...
    var jsVar = <?php echo json_encode($contents); ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?