在WordPress的通过XMLHttpRequest加载数据库内容(Loading databas

2019-08-31 16:05发布

我创建了一个新的WordPress的模板页面。 我们的想法是,当我点击我的侧边栏DIV的链接,它应该载入从我的内容DIV的数据库内容。 在一个简单的PHP页它的工作原理,但在我的WordPress模板的页面组合它不工作...

这是我的代码:(精简版)

<?php // Template Name: Weinkarte
get_header(); ?>

<div id="container-sidebar">
     <span id="wineList"></span>
</div>

<div id="sidebar-right">
    <li><a href='#' id='1' onclick='loadWine(this.id)'>Click</a></li>
</div>

get_footer();

<script>
function loadWine(id)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("wineList").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","loadWine.php?landID="+id,true); //I think here is probably the fault
xmlhttp.send();
}
</script>

谢谢你的帮助! :)

Answer 1:

在WordPress,你必须使用Ajax调用的动作,这样的事情(基本上是你的functions.php)

add_action( 'wp_ajax_nopriv_myAjaxFunction', 'myAjaxFunction' );  
add_action( 'wp_ajax_myAjaxFunction', 'myAjaxFunction' );
function myAjaxFunction(){  
    //get the data from ajax call  
    $landID = $_POST['landID'];
    // rest of your code
}

还可以使用post ,而不是get这样的事情在你的JavaScript文件

var data = "action=myAjaxFunction&landID="+id;
xmlhttp.open("POST","http://your_site.com/wp-admin/admin-ajax.php",true);
xmlhttp.send(data);

给出的例子只是一个想法,你应该阅读更多关于它,使用jQuery ,便于。 你可以阅读更多的食品和这里是另一个很好的文章 。



文章来源: Loading database content via XMLHttpRequest in Wordpress