2013-04-21 74 views
1

我创建了一个新的wordpress-template-page。这个想法是,当我点击我的sidebar-div中的链接时,它应该从我的content-div中的数据库加载内容。在一个简单的PHP页它的工作原理,但在我的WordPress模板的页面组合它不工作...在Wordpress中通过XMLHttpRequest加载数据库内容

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

<?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> 

感谢您的帮助! :)

回答

3

在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以方便。你可以阅读更多关于Codexhere is another nice article

+1

谢谢。现在它工作了! :D – Luca 2013-04-21 15:09:16

+0

欢迎您:) – 2013-04-21 15:40:42