我尝试弄清楚如何使用 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/