wordpress admin-ajax.php issues


wordpress admin-ajax.php issues

我正在做一个wordpress项目,遇到了一个令人沮丧的ajax问题。

我试图建立一个ajax调用从一个wordpress页面到一个php脚本,我叫getHistoricalTransFunctions.php。然后getHistoricalTransFunctions.php包含一个充满函数的文件,并运行我需要的函数。然后,所需的函数打印出一个响应,该响应被发送回我的javascript代码,然后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是做什么我需要做的最好的方法,我也想知道为什么这是不工作?谢谢!

首先你不应该修改核心文件。不需要将ajax函数添加到admin-ajax.php中。只需将add_action放在函数的正上方。此外,你的add_action在动作和函数名周围缺少引号(可能是在这里发布代码时的疏忽)。

此外,javascript ajaxurl变量在前端不可用,除非用户登录。你需要在js中定义变量:ajaxurl = 'http://your_site.com/wp-admin/admin-ajax.php';

对于admin-ajax.php,我必须使用输出缓冲才能使其正常工作:

 function runReport2() {
 ob_start ();
 //your code
 //end your code
$response = ob_get_contents ();
    ob_end_clean ();
    echo $response;
    die( 1 );