【发布时间】:2011-12-08 00:31:33
【问题描述】:
我正在做一个 wordpress 项目,但遇到了一个令人沮丧的 ajax 问题。
我正在尝试设置一个从 wordpress 页面到我称为 getHistoricalTransFunctions.php 的 php 脚本的 ajax 调用。 getHistoricalTransFunctions.php 然后包含一个充满函数的文件,并运行我需要的函数。然后所需的函数打印出一个响应,该响应被发送回我的 javascript 代码,然后显示响应。问题是,我试图调用的函数需要在 wordpress 环境中,因为它调用特定的 wordpress 函数。
我做了一些研究,发现 wordpress 在 admin-ajax.php 中提供了一个 ajax 处理程序。我学习了许多教程,包括:
http://codex.wordpress.org/AJAX_in_Plugins/
http://www.1stwebdesigner.com/css/implement-ajax-wordpress-themes/
http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
我已经关注了所有这些,但无论出于何种原因,我仍然从 admin-ajax.php 页面获得“-1”响应。我跟踪它,发现它源自 is_user_logged_in() 函数。显然 wordpress 认为我的用户没有登录,所以它在该代码块中出错。这是我的一些代码:
这是我的 javascript 调用:
$('button#RunReportButton2').click(function() {
$('#transactionContainer2').html("<img src='<?php echo $RootDomain; ?>/wp-content/themes/test-client/images/ajax-loader.gif' id='ajaxloader' style='margin: 170px auto auto 340px;' />");
var fromDate2 = $('#fromDate2').val();
var toDate2 = $('#toDate2').val();
$.ajax({ type: "POST",
url:ajaxurl,
type:'POST',
data: { action:"runReport2",
startingInt:"0",
fromDate:fromDate2,
toDate:toDate2 },
success: function(html) {
$('#transactionContainer2').html(html);
}
});
return false;
});
我在 admin-ajax.php 的底部添加了这个:
add_action(wp_ajax_nopriv_runReport2, runReport2);
add_action(wp_ajax_runReport2, runReport2);
那么我实际调用的php函数是:
function runReport2() {
include("$RootDomain/wp-content/themes/test-client/reports/historicalTransFunctions.php");
$startingIndex = $_POST['startingInt'];
//$startingIndex = 0;
$fromDate = $_POST['fromDate'];
//$fromDate = "2011-02-11";
$toDate = $_POST['toDate'];
//$toDate = "2011-12-05";
// post variable sanitization
if(!is_numeric($startingIndex)) {
printHistoricalTransactions($token, $client, 0);
die();
}
if($startingIndex <= 0) {
printHistoricalTransactions($token, $client, 0);
die();
}
// match date
$dateregex = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/';
if($toDate != "" && $fromDate != "") {
if(preg_match($dateregex, $fromDate) && preg_match($dateregex, $toDate))
printHistoricalTransactions($token, $client, $startingIndex, $fromDate, $toDate);
} else {
printHistoricalTransactions($token, $client, $startingIndex);
}
die();
}
我想知道 admin-ajax.php 是否是做我需要做的事情的最佳方法,我也想知道为什么这不起作用?谢谢!
【问题讨论】: