如何动态地将数据从PHP传递到JavaScript(在动态创建的HTML元素中)

时间:2016-07-08 06:20:33

标签: javascript php html ajax requirejs

我有一个从数据库填充的实体数组,每个实体都有自己的 GUID 。我通过循环实体数组并将每个数据放在一个新的动态创建的div包装器中,在网页(HTML)上显示它们。

<?php

$images = elgg_extract('entities', $vars, FALSE);

foreach ($images as $image) {
    $img = elgg_view_entity_icon($image, 'small');
    $image_guid = $image -> getGUID();

    echo <<<HTML
    <div class="file-preview-frame">
        <div class="image-preview">{$img}</div>
        <button type="button" class="btn-default" data-guid={$image_guid}></button>
    </div>
    HTML;
}

elgg_require_js('js/inline_image_view');

inline_image_view.js

require(['elgg/Ajax'], Ajax => {

    var ajax = new Ajax();

    $('.btn-default').click(function(event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var recipient = button.data('guid') // Extract info from data-* attributes

        ajax.view('albums/inline_full_image_view', {
            data: {
                guid: recipient // querystring
            },
        }).then(body => {
            $( '.full-image-view' ).html(body);
        })
    });
});

如何将每个按钮点击与RequireJS中的inline_image_view.js中的特定图像的GUID相关联?什么是最好或最好的方式来解决这个问题?

提前谢谢大家?

1 个答案:

答案 0 :(得分:0)

积分特别转到Elgg community Ismayil Khayredinov

<强>相册/ list.php的

<?php
$images = elgg_extract('entities', $vars);
echo elgg_view_entity_list($images, [
   'item_view' => 'albums/item_view',
   'no_results' => 'No images to show',
]);
?>
<div class="file-full-view-frame"></div>

<强>相册/ item_view.php

<?php
$image = elgg_extract('entity', $vars);
elgg_require_js('albums/item_view');

$img = elgg_view_entity_icon($image, 'small'); 
?>
<div class="file-preview-frame">
   <div class="image-preview"><?= $img ?></div>
   <?php
   echo elgg_view('input/button', [
      'class' => 'btn-default file-preview-show-full',
      'data-guid' => $image->guid,
   ], 'Show full'); 
   ?>
   </div>

</div>

<强>相册/ item_view.js

​define(function(require) {
  var Ajax = require('elgg/Ajax');
  var ajax = new Ajax();

  $(document).on('click', '.file-preview-show-full', function(e) {
     e.preventDefault();
     var $elem = $(this);
     var guid = $elem.data('guid');

     ajax.view('albums/inline_full_image-view', {
         //data: $elem.data(),
         data: {guid: guid}
     })
.done(function (output, statusText, jqXHR) {
        if (jqXHR.AjaxData.status == -1) {
            elgg.register_error('Unable to load full image view');
            return;
        }
        $('.file-full-view-frame').html(output);
    });
  });
});