PHP:'0' 被放置在 HTML 字符串的末尾

时间:2021-02-02 23:32:37

标签: javascript php jquery json

我在显示结束时得到一个“0”,这使 json_encode 显示错误 - “SyntaxError: JSON.parse: unexpected non-whitespace character 在 JSON 数据的第 1 行第 30 列的 JSON 数据之后"

在控制台中它看起来像 - "<div>nothing to show<\/div>"0

我曾尝试在 die; 之后或 echo 结束标记之后添加 else,正如我所读到的那样,可以在关于 SO 的另一个问题中解决该问题。但是,当添加到任一位置时,控制台会记录“空字符串”。我如何才能删除 0,或者如果 die 是正确的,它会去哪里?

function phpfuncname(){
$html_string = '';
        if($vairable){
            $html_string .= ' <div class="myclass">div content here</div>';
                {else{
                    $html_string .='<div>nothing to show</div>';  
                    echo json_encode($html_string);
                } 
}

查询:

        jQuery.ajax({
                type: 'post',
                url: my_ajax.ajax_url,
            dataType: 'JSON',
                data: {
                    action: 'php_function_name',
                }
            })
            .done(function(data) {
                jQuery('#waitlist').html(data.html);
            })
                .fail(function(xhr, status, error) {
                console.log(xhr.responseText); 
                alert(error); 
            })

1 个答案:

答案 0 :(得分:0)

那是因为你的 json_encode 编码的是一个字符串,而不是一个数组。当你的js代码接收到数据时,没有data.html,所以这是未定义的。

只需将其更改为

console.log(数据);

并看到您的文字出现。

要解决,你可以这样做:

echo json_encode( array( "html" => $html_string )); wp_die();

得到你想要的。 wp_die() 是必须的。

相关问题