2017-03-18 138 views
0

我正在为我的网站制作一种投票系统插件。当用户点击'like'按钮时,jQuery ajax应该将该点击发送给我的functions.php中的一个函数,我称其为vote_funct。 jQuery ajax脚本正在返回成功消息,但该函数根本不被调用。我不明白我做错了什么。下面是我的jQuery Ajax代码:jQuery Ajax函数不能在Wordpress中工作

(function($){ //wordpress jquery no conflict starts here 
$(document).ready(function($) { 
    var counter; 
    var id; 
    var ajaxurl = MyAjax.ajax_url; 

    $('.fa-plus').click(function(){ 
     counter = 0; 
     id  = $(this).closest('div').prop("id"); 
     counter = counter+1; 
     $(this).css('color','green'); 
     $(this).removeClass('fa fa-plus'); 
     $(this).addClass('fa fa-check');   

     $.ajax({ 
      url : ajaxurl, 
      type : "POST", 
      data : { 
         'action' : 'vote_funct', 
         'counter': counter, 
         'id'  : id 
         }, 
     success:function(data){ 
     console.log("counter"); 
    } 
     }).error(function(xhr, status){ 
      switch(status){ 
       case 404: 
        alert("404 not found"); 
        break; 
       case 500: 
        alert("500 server error"); 
        break; 
       case 0: 
        alert("0 request aborted"); 
        break; 
       default: 
        alert("unknown " + ajaxurl); 

      } 
    }); 
}) ;  
}); 
})(jQuery); 

然后我vote_funct这是位于functions.php的

$myfile = fopen("data.txt", "w") or die("Unable to open file!"); 
fwrite($myfile, json_encode($_POST)); 

function vote_funct(){ 
       $id = $_POST['id']; 
       $votes = $_POST['counter']; 

      if(!empty($_POST)){ 
       global $wpdb; 
       $wpdb->query($wpdb->prepare("UPDATE fwwp_votes SET votes = votes +1 WHERE id = $id")); 
      } 
      echo true; 
      die(); 
     } 
    add_action('wp_ajax_nopriv_vote_funct', 'vote_funct'); 
    add_action('wp_ajax_vote_funct', 'vote_funct'); 

仅供参考data.txt被写入所有的数据正确。

回答

0

根据您的jQuery的版本,您使用的是“错误”的功能可以被弃用(因为jQuery的3.0移除)..

如果是这样的情况下,尝试改变这种..

}).error(function(xhr, status){ 

到这(http://api.jquery.com/deferred.fail/)..

}).fail(function(){