Loading database content via XMLHttpRequest in Wordpress

混江龙づ霸主 提交于 2019-12-20 05:13:25

问题


I have created a new wordpress-template-page. The idea is, that when I click on a link in my sidebar-div, it should load content from an database in my content-div. On a simple php-page it works, but in combination with my wordpress template-page it doesn't work...

And that's my code: (short version)

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

Thanks for any help! :)


回答1:


In wordPress, you have to use action for ajax call, something like this (basically in your 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
}

Also use post instead of get something like this in you javascript file

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

Given example is just an idea, you should read more about it and use jQuery for ease. You can read more on Codex and here is another nice article.



来源:https://stackoverflow.com/questions/16127557/loading-database-content-via-xmlhttprequest-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!