2014-04-17 64 views
0

我正在使用一个(部分)停止工作的插件。作者没有那么敏感,所以我开始挖掘自己。WordPress的Ajax调用返回0

我已经到了认为我知道问题出在哪里的部分:ajax调用始终返回0。

如果有人能帮助我在这里?

从插件AJAX调用:

 var $this = $(this), 
     $parent = $this.parents('li'), 
     $container = $this.closest('.rwmb-uploaded'), 
     data = { 
      action: 'rwmb_delete_file', 
      _ajax_nonce: $container.data('delete_nonce'), 
      post_id: $('#post_ID').val(), 
      field_id: $container.data('field_id'), 
      attachment_id: $this.data('attachment_id'), 
      force_delete: $container.data('force_delete') 
     }; 

    $.post(ajaxurl, data, function(r) 
    { 
     console.log(ajaxurl); 
     console.log(data); 
     console.log(r); 
     if (!r.success) 
     { 
      alert(r.data); 
      return; 
     } 

     $parent.addClass('removed'); 

     // If transition events not supported 
     if (
      !('ontransitionend' in window) 
      && ('onwebkittransitionend' in window) 
      && !('onotransitionend' in myDiv || navigator.appName == 'Opera') 
     ) 
     { 
      $parent.remove(); 
      $container.trigger('update.rwmbFile'); 
     } 

     $('.rwmb-uploaded').on('transitionend webkitTransitionEnd otransitionend', 'li.removed', function() 
     { 
      $(this).remove(); 
      $container.trigger('update.rwmbFile'); 
     }); 
    }, 'json'); 

    return false; 

的的console.log(r)返回0,另外两个日志填充有正确的值。

的Ajax调用PHP代码:

static function add_actions() 
    { 
     // Add data encoding type for file uploading 
     add_action('post_edit_form_tag', array(__CLASS__, 'post_edit_form_tag')); 

     // Delete file via Ajax 
     add_action('wp_ajax_rwmb_delete_file', 'wp_ajax_delete_file'); 
    } 

static function wp_ajax_delete_file() 
    { 
     $post_id  = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; 
     $field_id  = isset($_POST['field_id']) ? $_POST['field_id'] : 0; 
     $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0; 
     $force_delete = isset($_POST['force_delete']) ? intval($_POST['force_delete']) : 0; 

     check_ajax_referer("rwmb-delete-file_{$field_id}"); 

     delete_post_meta($post_id, $field_id, $attachment_id); 
     $ok = $force_delete ? wp_delete_attachment($attachment_id) : true; 

     if ($ok) 
      wp_send_json_success(); 
     else 
      wp_send_json_error(__('Error: Cannot delete file', 'rwmb')); 
    } 

但似乎 'wp_ajax_delete_file' 从不执行。

我正在查看此代码现在几天没有找到解决方案。我不熟悉ajax,所以我不知道可能的解决方案的可能性。

如果您需要别的东西,我很乐意提供。

+0

您必须在ajax函数结束时使用die()函数来停止返回0值。 – ManoharSingh

+0

'exit()'也行,它们是别名。 –

回答

0

我认为你错过了这个钩子。这实际上适用于未登录的用户。

add_action('wp_ajax_nopriv_my_action', 'my_action_callback'); 
+0

它仅适用于管理员,因此未登录的用户对此部分并不重要。 但我做了一个干净的安装,它再次工作。 我也认为我找到了源代码。我从if循环中调用了ajax。那里有东西出错了。如果我在循环外调用ajax,即使对于内部调用也是如此。 所以现在我已经以不同的方式实现了插件,这对我来说很有用。 但无论如何感谢您的帮助。 – Yerlix

0

我做了一个干净的安装,它再次工作。我也认为我找到了来源。我从if循环中调用了ajax。那里有东西出错了。如果我在循环外调用ajax,即使对于内部调用也是如此。所以现在我已经以不同的方式实现了插件,这对我来说很有用。

对不起,我没有发布这个更快,Stackoverflow没有让我。