【问题标题】:How to bind an include to a associative array in php [duplicate]如何将包含绑定到php中的关联数组[重复]
【发布时间】:2019-04-12 17:16:48
【问题描述】:

我有 2 个来自 php 脚本的回显,它们作为 json 发送到 ajax 调用。这 2 个回声将在 2 个不同的 div 中输出。 对于这 2 个回声,我创建了一个如下所示的数组:

 $result = [
    "one" => "this is echo 1",
    "two" => "this is echo 2"
];
echo json_encode($result);

我现在想要包含 2 个文件(这将是回声),而不是这些回声。母猪我能做到吗?

所以我想要的是这样的:

$result = [
    "one" => include('success.php'),
    "two" => include('renderfiles.php')
];

我该怎么做?

顺便说一下,这是我的 jquery ajax:

$.ajax({
url: "",
type: "post",
data:  new FormData(this),
dataType: 'json',
contentType: 'application/json',
    success: function(data) {
       $('.echo').html(data.one); // content ofinclude success.php should come here
   $('.table-content').html(data.two); // content of include renderfiles.php should come here

【问题讨论】:

  • 你期望success.php包含什么?
  • 在两个包含中都是带有 html 的 php 代码
  • 您将收到包含的结果(0 或 1),而不是内容...如果您需要未解析的 PHP,请使用 file_get_contents,使用已解析的 html,使用 outputbueffering 截取直接输出。

标签: php json ajax include associative-array


【解决方案1】:

在您的包含文件中,您需要return HTML - 或使用output buffering 捕获它,然后返回内容。使用return ...

$result = [
    "one" => include('success.php'),
    "two" => include('renderfiles.php')
];

所以success.php的内容应该是这样的

return "<sometag></sometag>";

这可以确保将值传回并插入正确的位置,并会给出类似

{"one":"<sometag><\/sometag>","two":...}

如果你只是echo HTML,

echo "<sometag></sometag>";

你可能会得到类似的东西

<sometag></sometag>{"one":1,"two":"a"}

【讨论】:

    【解决方案2】:

    "one" => include('success.php'),只会将文件的返回值放入数组的“one”元素中。如果您不从中返回任何内容,则它将为空。

    如果你想要输出,你需要使用输出缓冲:

    ob_start();
    require_once('success.php');
    $var = ob_get_clean();
    

    但我会建议你只发送你想要包含的文件的名称,然后你可以将这些包含的内容加载到一个带有 php 的部分,或者使用 ajax 发送 html 内容

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2015-06-08
      • 2013-06-17
      • 2017-10-26
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多