Wordpress-使用jQuery ajax POST请求获取用户信息


Wordpress - fetch user info using jQuery ajax POST request

我在Wordpress工作,试图使用ajax请求通过传递用户id来获取用户数据。

我可以看到用户id通过AJAX POST正确发送,但我收到了一条内部错误消息,我不知道为什么。

起初我以为这是因为我试图获取一些添加到用户配置文件中的自定义字段,但即使我简化了脚本,我仍然会收到错误消息。

非常感谢您的帮助!

前端

$('.author').click(function() {
    var id   = $(this).attr('id');
    var temp = id.split('-');
    id = temp[1];
    $.ajax({
            type: 'POST',
            url: 'wp-content/themes/twentyeleven/author_info.php',
            data: {id: id},
            dataType: 'html',
            success: function(data) {
                $('#author-bio').html(data);        
            }
        });     
    return false;
});

author_info.php

$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;

错误消息

500 (Internal Server Error) jquery.min.js:4

Mathieu添加了一种可破解的方法来拦截请求并重定向它,这很好。我更喜欢构建返回json_encoded数组的AJAX响应。

$('.author').click(function() {
  var id   = $(this).attr('id');
  var temp = id.split('-');
  id = temp[1];
  $.ajax({
    url: 'http://absolute.path/wp-admin/admin-ajax.php',
    data: {'action' : 'ajax_request', 'fn': 'getAuthorMeta', 'id': id},
    dataType: 'json',
    success: function(data) {
      //We expect a JSON encoded array here, not an HTML template.       
    }
  });     
  return false;
});

现在我们构建了处理ajax请求的函数。

首先,我们需要定义我们的ajax add_action方法->

add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');

我们需要在这里使用两条add_action线路。我不想说为什么。你会注意到这里的_ajax_request。这是我们在AJAX函数data: {'action' : 'ajax_request'}中发送的"操作"。我们使用这个钩子来验证我们的AJAX请求,它可以是你想要的任何东西。

接下来,我们需要构建或运行ajax_handle_request

function ajax_handle_request(){
  switch($_REQUEST['fn']){
    case 'getAuthorMeta':
      $output = ajax_get_author_meta($_REQUEST['id']);
      break;
    default:
      $output = 'That is not a valid FN parameter. Please check your string and try again';
      break;
  }
  $output = json_encode($output);
  if(is_array($output)){
    return $output;
  }else{
    echo $output;
  }
}

现在,让我们构建我们的函数来实际获取作者元。

function ajax_get_author_meta($id){
  $theMeta = get_the_author_meta([meta_option], $id);
  return $theMeta;
}

其中[meta_option]是WP的本地get_the_author_meta函数提供的字段。

此时,我们将返回到success:function(data),(data)是对我们返回的json_encoded数组的引用。我们现在可以对对象进行迭代以获得字段,并根据需要将它们输出到页面中。

您现在没有POST,因为您正在调用模板的特定页面,该页面可能与博客中的任何文章都不对应。

相反,创建一个插件来实现这一点:

add_action('template_redirect', 'my_author_meta_intercept');
function my_author_meta_intercept(){
    if(isset($_POST['getAuthorMeta'])){
        echo get_the_author_meta('user_firstname', $_POST['getAuthorMeta']);
        exit();
    }
}

当您使用调用时,这将使请求短路到与以前相同的页面

http://mysite/mycurrenturl?getAuthorMeta=testMetaKey

所以,正常拨打该帖子会像往常一样返回文章,但如果你错过了?getAuthorMeta,它将停止选择模板,并简单地返回您希望它返回的确切内容。

在您的页面中,您只需将javascript更改为:

$('.author').click(function() {
    var id   = $(this).attr('id');
    var temp = id.split('-');
    id = temp[1];
    $.ajax({
            type: 'POST',
            url: window.location.href,
            data: {getAuthorMeta: id},
            success: function(data) {
                $('#author-bio').html(data);        
            }
        });     
    return false;
});

只要确保你将这个概念适应你的需要!

我建议您使用WP AJAX操作方法。

与您的情况一样,将以下内容添加到functions.php文件中。

 add_action('wp_ajax_get_user_info', 'ajax_get_user_info');
 add_action('wp_ajax_nopriv_get_user_info', 'ajax_get_user_info');
 function ajax_get_user_info() {
    //Handle request then generate response using WP_Ajax_Response or your html.
 }

然后在javascript标记中。

$('.author').click(function() {
    var id   = $(this).attr('id');
    var temp = id.split('-');
    id = temp[1];
jQuery.post(
   ajaxurl,  /* if you get error of undefined ajaxurl. set it to "http://example.com/wordpress/wp-admin/admin-ajax.php"*/
   {
      'action':'get_user_info',
      'user_id':id
   }, 
   function(response){
      alert('The server responded: ' + response);
   }
);
});

我建议你阅读在WordPress中使用AJAX的5个技巧。

p.s;上面的代码没有经过测试,可能有错误。但你明白了。