发送ajax请求无效的Html格式

时间:2016-01-21 13:39:00

标签: javascript php jquery ajax wordpress

我试图在将其发送到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 ) ) );

我确信我做错了什么:(

1 个答案:

答案 0 :(得分:0)

我认为这是一个WordPress问题,get_categories返回一个对象数组(https://codex.wordpress.org/Function_Reference/get_categories)。

执行以下操作:

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

...或根据WordPress Codex文档所需的任何内容。