簡體   English   中英

如何將數據從PHP動態傳遞到JavaScript(在動態創建的HTML元素中)

[英]How to dynamically pass data from PHP to JavaScript (In dynamically created HTML elements)

我有一個從數據庫填充的實體數組,每個實體都有自己的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相關聯? 最好的或首選的方法是什么?

謝謝大家?

感謝Elgg社區 ,尤其是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);
    });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM