所以,我有以下ajax调用:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
然后我的php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
正如您所看到的,在php函数中,有两个单独的事情发生。
echo $tag->term_id;
显示的是这样的数字“16508164981650616502165031650416505165071650116520”。所以,不知何故,我需要在每个术语ID(不确定如何)之间加上逗号,所以它看起来像这样:“16508,16498,16506,16502,16503,16504,16505,16507,16501,16520”another_php
文件传递给js(工作正常)。问题:
编辑:使用json_encode传递数据
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
答案 0 :(得分:1)
要在两者之间添加逗号,您可以使用变量来存储而不是立即回显。像这样:
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;
答案 1 :(得分:1)
使用json_encode
发送包含前端所需数据的数组,然后需要对ajax函数进行以下更改。
dataType
更改为json
data.another_php
和data.tag_id
完整的ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});