WordPress中如何通过Ajax将不同内容追加到多个Div?
解决AJAX响应分类并向多个Div追加内容的方案
要实现同时给两个Div分别填充不同内容,你需要把AJAX响应改成结构化JSON对象,将两类内容分开返回,再在前端分别处理。具体修改如下:
修改PHP端(ajax_filter.php)
原代码仅返回模板渲染内容,现在需要把两类内容打包成关联数组,通过wp_send_json_success返回:
function search_checkbox_call() { $cat_clug = $_POST['category']; $args = array( 'post_type' => 'page', 'category__and' => $cat_clug, 'post_status' => 'publish', 'orderby' => 'DESC' ); $new = new WP_Query($args); ob_start(); if ($new->have_posts()) { while ($new->have_posts()) { $new->the_post(); get_template_part('template-parts/content-search'); } grupi_posts_pagination(); } else { get_template_part('template-parts/content', 'none'); } // 捕获模板渲染的内容 $result_content = ob_get_clean(); $test = "<div class='test'><h1>Test</h1></div>"; // 返回包含两类内容的JSON对象 wp_send_json_success(array( 'result_content' => $result_content, 'filter_content' => $test )); exit; } add_action('wp_ajax_search_checkbox_call', 'search_checkbox_call'); add_action('wp_ajax_nopriv_search_checkbox_call', 'search_checkbox_call');
修改JS端(filter.js)
前端无需手动JSON.parse(dataType: 'json'已自动解析响应),直接从返回的data属性中取出对应字段,分别更新目标Div:
jQuery(document).ready(function(){ jQuery('.category_checkbox, .services_checkbox, .industry_checkbox').click(function(){ var category = jQuery('input[name=category_checkbox]:checked').map(function() { return jQuery(this).val(); }).get(); var services = jQuery('input[name=services_checkbox]:checked').map(function() { return jQuery(this).val(); }).get(); var industry = jQuery('input[name=industry_checkbox]:checked').map(function() { return jQuery(this).val(); }).get(); jQuery.ajax({ url: my_ajax_object.ajax_url, type: 'post', dataType: 'json', data: { action: "search_checkbox_call", category: category, services: services, industry: industry }, success:function(response){ // 覆盖Div原有内容 jQuery('#result_data').html(response.data.result_content); jQuery('#filter').html(response.data.filter_content); // 如果是追加内容而非覆盖,替换成以下两行 // jQuery('#result_data').append(response.data.result_content); // jQuery('#filter').append(response.data.filter_content); } }); }); });
关键说明
wp_send_json_success会自动将响应封装为标准格式,前端通过response.data即可获取我们定义的内容数组。- 若需求是追加内容而非覆盖,将
html()方法替换为append()即可。
内容的提问来源于stack exchange,提问作者Sanad Cal
相关产品推荐
相关产品推荐

