2014-09-06 112 views
3

我正在使用WordPress AJAX动态加载子类别。WordPress的AJAX返回HTML

这里是我的代码

PHP代码

function techento_getsubcat() { 
    $category_name = $_POST['catname']; 
    $cat_id = $_POST['catid']; 
    return wp_dropdown_categories('show_option_none=Choose a Sub    Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . ''); 

    } 
    add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat'); 
    add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat'); 

jQuery的

 jQuery(document).ready(function(){ 
    $('#cat').change(function(e){ 
    alert("changed"); 

    $.ajax({ 
     type: 'POST', 
     dataType: 'json', 
     url: pcAjax.ajaxurl , 
     data: { 
      'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin 
      'catname': $('#cat option:selected').text(), 
      'catid': $('#cat option:selected').val() }, 
     success : function(response){ 
       alert(response); 
      console.log(response); 

      $("#subcats").html(response); 

     } 
    }); 
    e.preventDefault(); 

     }); 
    }); 

与上面的代码的问题是,PHP不考虑返回要求返回

事物的原始HTML

即使将其设置为

return true; 

它然后返回生成的子类别的原始HTML加 '0'

+0

设置'dataType'只是告诉'$ .ajax'期待作为返回什么,它不会改变从服务器返回的内容。真的不清楚你的问题是什么 – charlietfl 2014-09-06 17:57:37

+0

我已经设置“返回true”但尽管它返回HTML生成从wp_dropdown_category @charlietfl – 2014-09-06 18:01:24

+0

'返回true'什么?你的解释不是很详细 – charlietfl 2014-09-06 18:02:15

回答

4

你错过了在

jQuery(document).ready(function($){ 

$简码的Ajax回调是更好地wp_send_json_success()处理,所以我们不必担心returnecho,exitdie。为此,在dropdown arguments设置echo为false:

function techento_getsubcat() { 
    $cat_id = intval($_POST['catid']); 
    $args = array(
     'hide_empty'   => 0, 
     'echo'    => 0, 
     'child_of'   => $cat_id, 
     'taxonomy'   => 'category' 
    ); 
    $data = wp_dropdown_categories($args); 
    wp_send_json_success($data); 
} 

在阿贾克斯成功,使用response.data

success : function(response){ 
    console.log(response.data); 
}