Vai*_*ali 3 javascript php ajax wordpress jquery
我正在使用 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');
Run Code Online (Sandbox Code Playgroud)
查询
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();
});
});
Run Code Online (Sandbox Code Playgroud)
上面代码的问题是 php 返回原始 html 而不考虑要求返回的内容
即使将其设置为
return true;
Run Code Online (Sandbox Code Playgroud)
然后返回生成的子类别的原始 html 加上“0”
你错过了$
短代码
jQuery(document).ready(function($){
Run Code Online (Sandbox Code Playgroud)
Ajax 回调由 更好地处理wp_send_json_success()
,因此我们不必担心return
或echo
、exit
或die
。为此,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 );
}
Run Code Online (Sandbox Code Playgroud)
在 Ajax 成功时,使用response.data
:
success : function(response){
console.log(response.data);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10114 次 |
最近记录: |