[英]Wordpress ajax returning html
Am using WordPress ajax to load the sub-categories dynamically. 我使用WordPress ajax动态加载子类别。
Here's my code 这是我的代码
Php code 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的
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();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return 上面代码的问题是php返回原始html而不管要求返回的内容
even if set it to 即使设置为
return true;
it then returns the raw html of subcategories generated plus '0' 然后它返回生成的子类别的原始html加'0'
You're missing the $
shortcode in 你错过了
$
shortcode
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success()
, so we don't have to worry with return
or echo
, exit
or die
. wp_send_json_success()
可以更好地处理Ajax回调,因此我们不必担心return
或echo
, exit
或die
。 For that, set echo
to false in the 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 );
}
On Ajax success, use response.data
: 在Ajax成功时,使用
response.data
:
success : function(response){
console.log(response.data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.