开发者

Alternative way to build HTML data for an asynchronous request

开发者 https://www.devze.com 2023-04-08 10:16 出处:网络
So there\'s typically 2 ways I\'ll return data for an AJAX request. Either as a data set or a ready-to-append DOM element.

So there's typically 2 ways I'll return data for an AJAX request. Either as a data set or a ready-to-append DOM element.

1: Data set

echo json_encode(array(
    'status'=>200,
    'meta' => 'associated info',
    'id'=> 123,
    'data' => "<div>some stuff to add to the page</div>"
));

2: HTML

<?php function ajaxRequest() { ?>
    <div>some stuff to add to the page</div>
<?php } ?>

Is there any way to use a hybrid of these two methods? I doubt it, but can I have the exterior-php html content be embedded into the data set? Rather than it being output, any way for it to be input for a variable?

Basically I'd like to build the HTML without any string building. Something like this (obviou开发者_JAVA技巧sly this wont work):

<?php function ajaxRequest() {
    return json_encode(array(
        'status'=>200,
        'meta'=>'associated_info',
        'id'=>123,
        'data'=>
        ?>
    <div>some stuff to add to the page</div>
<?php 
    ));
  } 
?>

So -- is there a way, which I doubt since the content lives outside the php sections, to have this content return into the php?


Use ob_start() and ob_get_clean() to wrap your HTML generation in to create a string, like this:

<?php
ob_start();
?>
<div>Stuff</div>
<?php
$var = ob_get_clean();
0

精彩评论

暂无评论...
验证码 换一张
取 消