我想从PHP脚本返回JSON。

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


当前回答

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

其他回答

如果你需要从发送自定义信息的php中获取json,你可以添加这个头('Content-Type: application/json');在打印任何其他东西之前,所以然后你可以打印你的自定义echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

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

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

如果你想要js对象,使用头content-type:

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

如果你只想要json: remove header content-type属性,只需要encode和echo。

<?php
$data = /** whatever you're serializing **/;
echo json_encode($data);