这个问题在这里已有答案:
我有一个来自php脚本的2个echo,它们作为json发送到ajax调用。这2个回声将以2个不同的div输出。对于那些2个echo,我创建了一个如下所示的数组:
$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
......
$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'),只会将文件的返回值放入数组的“one”元素中。如果你没有从它返回任何东西,它将只是为空。
如果您想要输出,则需要使用输出缓冲:
ob_start();
require_once('success.php');
$var = ob_get_clean();
但我建议你只发送你想要包含的文件的名称,然后你可以将这些包含的内容加载到php的一个部分,或者使用ajax发送html内容
希望能帮助到你