Wordpress AJAX with raw javascript? NO Jquery

Wordpress AJAX with raw javascript? NO Jquery

本文关键字:NO Jquery javascript raw AJAX with Wordpress      更新时间:2023-09-26

好吧,所以我有一个相关的posts.php脚本,我希望只有在特定的用户操作(滚动)时才能将其插入到posts中。我还有一个脚本文件,它由wordpress排队并加载在页脚中——在那里我写了这样的ajax:

var  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("relatedPosts").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","http://localhost/wordpress/wp-content/themes/mytheme/functions/widgets/ajaxa.php",true);
  xmlhttp.send();

AJAX加载文件,但问题是:php脚本似乎"不知道"它加载的页面,因为

global $post; 
print_r($post);

输出0(零)。。。

我知道在wordpress中有一种正确的使用ajax的方法,但我发现的所有文档都严重依赖于Jquery(我现在不知道也不想学习)

如何仅使用javascript使其工作?

您的PHP代码不知道全局$post对象,因为它没有与页面的其他部分一起编译-您需要将它们视为两个独立的页面,除非它们保存在会话中,否则它们不会在PHP中共享对象,因为它们是独立编译的。

如果你想找到相关的帖子,你应该把主帖子的id传递给生成关联的PHP脚本,然后用它在ajax.PHP中查找相关项目…例如

var  xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
     document.getElementById("relatedPosts").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","...mypath.../ajaxa.php?getAssociationsFor=<?php get_the_ID(); ?>",true);
xmlhttp.send();

然后在ajaxa.php中,类似于。。。

htmlspecialchars($_GET["getAssociationsFor"])

以获取从HTML页面传递的值。