【问题标题】:How can I show the raw json string in wordpress api如何在 wordpress api 中显示原始 json 字符串
【发布时间】:2021-07-29 05:30:30
【问题描述】:

在我的自定义 wordpress api 端点上出现此错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我该如何调试它?我想看看无法解析的实际 json 字符串。这有可能吗?

这是我的回调函数:

function get_price_callback() {

    $resp = get_price('25-05-2021','Depoistum');
    $val = htmlspecialchars($resp);
        
    $type = htmlspecialchars( $_GET["type"] );
    return rest_ensure_response([$date]);
    }

get_price('25-05-2021','Depoistum') // will return 5000

【问题讨论】:

    标签: wordpress api wordpress-theming wordpress-rest-api


    【解决方案1】:

    您可以使用 wordpress wp_send_json_successwp_send_json_error 函数。所以你的回调函数会是这样的:

    
    function get_price_callback(){
    
        $resp = get_price('25-05-2021','Depoistum');
    
        $val = htmlspecialchars($resp); // You could also use wordpress "esc_html" function for sanitization instead! 
            
        $type = esc_html( $_GET["type"] ); // or sanitize_text_field() function
    
        $data = array($val, $type);
      
        wp_send_json_success($date); 
    
       // or you could send it via  "wp_send_json_error", if you need to!
    }
    

    您可以在文档页面上阅读有关这两个函数的更多信息。

    WordPress wp_send_json_success function
    WordPress wp_send_json_error function

    【讨论】:

    • 将return语句替换为:wp_send_json_error($date);没有区别。
    • 就像我说的,wp_send_json_success 是以 json 格式发送数据的 wordpressish 方式。如果你不能让它工作,可能是你的前端代码中的某个地方存在你没有向我们展示的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2011-03-05
    • 2014-12-27
    • 1970-01-01
    • 2022-08-03
    • 2017-09-09
    • 2012-06-01
    相关资源
    最近更新 更多