【问题标题】:Wordpress ajax returning htmlWordpress ajax 返回 html
【发布时间】:2014-10-31 10:02:49
【问题描述】:

我正在使用 WordPress ajax 动态加载子类别。

这是我的代码

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”

【问题讨论】:

  • 设置dataType 只是告诉$.ajax 期望返回什么,它不会改变从服务器返回的内容。真的不清楚你的问题是什么
  • 我设置了“return true;”但尽管它返回 html generate from wp_dropdown_category @charlietfl
  • return true 关于什么?你的解释不是很详细
  • 这是我得到的响应“i.imgur.com/Ks9vs7B.png”唯一的预期响应是“0”,因为出于测试目的,它使它返回 true
  • 你能整理一下你的代码吗?此外,php 函数techento_getsubcat 应该在末尾有一个die();,并且不要返回wp_dropdown...,因为它已经回显了

标签: javascript php jquery ajax wordpress


【解决方案1】:

您缺少 $ 短代码

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

wp_send_json_success() 更好地处理 Ajax 回调,因此我们不必担心 returnechoexitdie。为此,在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);
}

【讨论】:

猜你喜欢
  • 2015-07-15
  • 1970-01-01
  • 2015-06-01
  • 2015-09-06
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多