javascript-WordPress ajax返回html

我正在使用wordpress ajax动态加载子类别.

这是我的代码

邮递区号

  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”

解决方法:

您错过了$短代码

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

wp_send_json_success()可以更好地处理Ajax回调,因此我们不必担心return或echo,exit或die.为此,在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 );
}

如果Ajax成功,请使用response.data:

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

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...