在 Wordpress 中通过 XMLHttpRequest 加载数据库内容
我创建了一个新的 wordpress-template-page.这个想法是,当我单击侧边栏 div 中的链接时,它应该从我的内容 div 中的数据库加载内容.在一个简单的 php 页面上它可以工作,但结合我的 wordpress 模板页面它不起作用......
这就是我的代码:(简短版本)
<?php//模板名称:Weinkarteget_header();?><div id="容器侧边栏"><span id="wineList"></span><div id="sidebar-right"><li><a href='#' id='1' onclick='loadWine(this.id)'>点击</a></li>
get_footer();<脚本>函数 loadWine(id){xmlhttp=新的 XMLHttpRequest();xmlhttp.onreadystatechange=function(){如果(xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("wineList").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","loadWine.php?landID="+id,true);//我认为这里可能是错的xmlhttp.send();}
感谢您的帮助!:)
解决方案在 wordPress 中,你必须使用 action 进行 ajax 调用,类似这样(基本上在你的functions.php 中)
add_action('wp_ajax_nopriv_myAjaxFunction', 'myAjaxFunction');add_action('wp_ajax_myAjaxFunction', 'myAjaxFunction');函数 myAjaxFunction(){//获取ajax调用的数据$landID = $_POST['landID'];//其余代码}
在你的 javascript 文件中也使用 post
而不是 get
类似的东西
var data = "action=myAjaxFunction&landID="+id;xmlhttp.open("POST","http://your_site.com/wp-admin/admin-ajax.php",true);xmlhttp.send(数据);
给出的例子只是一个想法,你应该阅读更多关于它并使用 jQuery
来轻松.您可以在 Codex 和 这是另一篇不错的文章.
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! :)
解决方案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.
相关文章