dougang1965 2015-03-20 15:48
浏览 38

Wordpress AJAX与原始的JavaScript? 没有Jquery

Alright, so I have a related-posts.php script I wrote and I wish to insert it into posts only upon certain user action (scrolling). I also have a script file which is enqueued by wordpress and loads in footer - in there I've written ajax like so:

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 loads the file, however the problem is: the php script seems to be 'unaware' of the page it loads in since

global $post; 
print_r($post);

outputs 0 (zero)...

I understand there's a proper way of using ajax in wordpress however all the documentation I found relies heavily on Jquery (which I don't know nor wish to learn at the moment)

How can I make it work using javascript solely?

  • 写回答

1条回答 默认 最新

  • dsfsfsfsfs55656 2015-03-20 16:03
    关注

    Your PHP code is unaware of the global $post object because it is not compiled with the rest of the page - you need to think of these as two separate pages that do not share objects in PHP unless they are saved in the session since they are compiled independently.

    If you want to find related posts, you should pass the id of the main post to the PHP script generating the associations, then use that to look up the related items within ajax.php... e.g.

    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();
    

    Then in ajaxa.php something like...

    htmlspecialchars($_GET["getAssociationsFor"])
    

    to get the value passed from the HTML page.

    评论

报告相同问题?

悬赏问题

  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现