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

问题描述 投票:0回答:1

我试图找出如何使用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...";
                    };
                  }
                }

我有一个帖子,我试着加载绑定到这篇文章的图像。 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请求单击按钮后,我想用图像加载此循环,但我需要帮助如何请求动态数据。

谢谢您的帮助。

javascript php wordpress xmlhttprequest
1个回答
2
投票

在wordpress主题上使用ajax时,你应该使用wordpress ajax action hooks 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();
}

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

© www.soinside.com 2019 - 2024. All rights reserved.