要发送的 ajax 请求的 html 格式不起作用

Html format to send for ajax request not working

本文关键字:html 格式 不起作用 请求 ajax      更新时间:2023-09-26

我正在尝试在将html格式发送到ajax请求之前获取html格式。但是发生了这样的错误:Error: SyntaxError: Unexpected token < - parsererror - [object Object]

我只想通过数组中的值进行选择选项。这是代码:

$args = array(
    'type'        => 'ad_listing',
        'child_of'    => $parent_cat,
        'orderby'     => 'name',
        'order'       => 'ASC',
        // 'hide_empty'  => 1,
        // 'hierarchical'=> 1,
        'exclude'     => '',
        'include'     => '',
        'number'      => '',
        'taxonomy'    => 'ad_cat',
        'pad_counts'  => false 
);
$results = get_categories( $args );
$result = '<select>';
foreach ($results as $key => $value) {
    $result .= '<option>' . $value . '</option>';
}
return $result .= '</select>';
// return the result to the ajax post
die( json_encode( array( 'success' => true, 'html' => $result ) ) );

在这里$result将是我要发送的 html 格式。错误来了:Error: SyntaxError: Unexpected token < - parsererror - [object Object]

但是如果我以这种方式使用代码,我会得到数组对象:

    $args = array(
    'type'        => 'ad_listing',
        'child_of'    => $parent_cat,
        'orderby'     => 'name',
        'order'       => 'ASC',
        // 'hide_empty'  => 1,
        // 'hierarchical'=> 1,
        'exclude'     => '',
        'include'     => '',
        'number'      => '',
        'taxonomy'    => 'ad_cat',
        'pad_counts'  => false 
);
$result = get_categories( $args );

// return the result to the ajax post
die( json_encode( array( 'success' => true, 'html' => $result ) ) );

确定我做错了什么:(

正如我假设这是一个 WordPress 问题get_categories返回一个对象数组 (https://codex.wordpress.org/Function_Reference/get_categories)。

执行以下操作:

foreach($results as $cat) {
$result .= '<option>'.$cat->name.'</option>';
}

。或者根据WordPress Codex文档需要的任何内容。