Loading database content via XMLHttpRequest in Wor

2019-02-27 19:55发布

问题:

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.