我想从PHP脚本返回JSON。

我只是重复结果吗?我必须设置内容类型头吗?


当前回答

是的,你需要使用echo来显示输出。Mimetype: application / json

其他回答

<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>

返回JSON的完整的PHP代码如下:

$option = $_GET['option'];

if ( $option == 1 ) {
    $data = [ 'a', 'b', 'c' ];
    // will encode to JSON array: ["a","b","c"]
    // accessed as example in JavaScript like: result[1] (returns "b")
} else {
    $data = [ 'name' => 'God', 'age' => -1 ];
    // will encode to JSON object: {"name":"God","age":-1}  
    // accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}

header('Content-type: application/json');
echo json_encode( $data );

用header(' content -type: application/json')设置内容类型;然后对数据进行回显。

尝试json_encode对数据进行编码,并设置带有header的content-type (' content-type: application/json');

如果你在WordPress中这样做,那么有一个简单的解决方案:

add_action( 'parse_request', function ($wp) {
    $data = /* Your data to serialise. */
    wp_send_json_success($data); /* Returns the data with a success flag. */
    exit(); /* Prevents more response from the server. */
})

请注意,这不在wp_head钩子中,该钩子将始终返回大部分头部,即使您立即退出。parse_request在序列中出现得更早。