如何将包含绑定到 php 中的关联数组

How to bind an include to a associative array in php

我有 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

在您的包含文件中,您需要 return HTML - 或使用 output buffering 捕获它然后 return 内容。使用 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"}

"one" => include('success.php'),只会将文件的 return 值放入数组的 "one" 元素中。如果您不 return 从中获取任何内容,它将只是空的。

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

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

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

希望对您有所帮助