javascript - 使用 Ajax 请求加载 php 循环(或类似的 Javascript 解决方案)

标签 javascript php wordpress xmlhttprequest

我尝试弄清楚如何使用 xmlhttp 请求加载一小段数据(php 循环)。

我正在使用的函数工作正常,但是我只想加载文件“gallery.php”中的 php 循环:

function refreshData(){

                  var display = document.getElementById("content");
                  var xmlhttp = new XMLHttpRequest();

                  xmlhttp.open("GET", "<?php echo esc_url( home_url( '/' ) ) ?>gallery/");
                  xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                  xmlhttp.send();

                  xmlhttp.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                      display.innerHTML = this.responseText;
                    } else {
                      display.innerHTML = "Loading...";
                    };
                  }
                }

我有一篇文章,我正在尝试加载绑定(bind)到该文章的图像。 gallery.php 中的循环在这里:

<?php $images = get_attached_media( 'image' );

            foreach($images as $image) { ?>
                <div>
                    <img src="<?php echo wp_get_attachment_url($image->ID,'full'); ?>"/>
                </div>
            <?php } ?>

我想在使用 xmlhttp 请求单击按钮后用图像加载此循环,但我确实需要帮助如何请求动态数据。

感谢您的帮助。

最佳答案

在 wordpress 主题上使用 ajax 时,您应该使用 wordpress ajax 操作 Hook https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

例如:

add_action( 'wp_ajax_get_galleryimage', 'get_galleryimage' );

function get_galleryimage() {
// than here you put the code to get the images of the given posts, you 
//should send post id from the js  

// Don't forget to stop execution afterward.
wp_die();
}

你不需要为此创建一个页面,使用钩子(Hook)你的ajax调用将在这个url上,homeurl../wp-admin/admin-ajax.php?action=get_galleryimage

关于javascript - 使用 Ajax 请求加载 php 循环(或类似的 Javascript 解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47962174/

相关文章:

javascript - 如何在 Visual Studio 2010/2012 中将自定义文件扩展名注册到 JavaScript 编辑器?

php - 在多个 php 页面之间共享功能的最有效方法

PHP < 5.3,create_function 和使用变量

php - 将数字数组和带连字符的数字范围扩展为整数数组

JAVA_HOME 无效(cordova)错误

php - mod_rewrite : Demystifying RewriteBase (once and for all)

php - 将购买特定产品的客户从单一产品页面重定向

javascript - 在 SpriteStage 上使用 SpriteSheet 渲染的动画无法正确显示

javascript - 在 asp.net MVC 中使用外部 javascript 文件

javascript - 使用replace从html中删除<strong>标签