tim*_*dev 1483
虽然没有它你通常很好,你可以并且应该设置Content-Type标题:
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
如果我没有使用特定的框架,我通常会允许一些请求参数来修改输出行为.它通常用于快速故障排除,不发送标题,或者有时print_r数据有效负载以引人注目(尽管在大多数情况下,它不是必需的).
aes*_*ede 114
返回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 );
Run Code Online (Sandbox Code Playgroud)
tri*_*cot 39
根据手册上json_encode的方法可以返回非字符串(false):
成功或
FALSE失败时返回JSON编码的字符串.
发生这种情况时,echo json_encode($data)将输出空字符串,这是无效的JSON.
json_encode例如,false如果其参数包含非UTF-8字符串,则会失败(并返回).
应该在PHP中捕获此错误情况,例如:
<?php
header("Content-Type: application/json");
// Collect what you need in the $data variable.
$json = json_encode($data);
if ($json === false) {
// Avoid echo of empty string (which is invalid JSON), and
// JSONify the error message instead:
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
// Set HTTP response status code to: 500 - Internal Server Error
http_response_code(500);
}
echo $json;
?>
Run Code Online (Sandbox Code Playgroud)
然后接收端当然应该知道jsonError属性的存在表明错误条件,它应该相应地处理.
在生产模式下,最好只向客户端发送一般错误状态,并记录更具体的错误消息以供以后调查.
son*_*que 17
这个问题有很多答案,但没有一个涵盖返回干净 JSON 的整个过程,以及防止 JSON 响应格式错误所需的一切。
/*
* returnJsonHttpResponse
* @param $success: Boolean
* @param $data: Object or Array
*/
function returnJsonHttpResponse($success, $data)
{
// remove any string that could create an invalid JSON
// such as PHP Notice, Warning, logs...
ob_clean();
// this will clean up any previously added headers, to start clean
header_remove();
// Set the content type to JSON and charset
// (charset can be set to something else)
header("Content-type: application/json; charset=utf-8");
// Set your HTTP response code, 2xx = SUCCESS,
// anything else will be error, refer to HTTP documentation
if ($success) {
http_response_code(200);
} else {
http_response_code(500);
}
// encode your PHP Object or Array into a JSON string.
// stdClass or array
echo json_encode($data);
// making sure nothing is added
exit();
}
Run Code Online (Sandbox Code Playgroud)
参考:
Dr.*_*hno 12
设置访问安全性也很好 - 只需将*替换为您希望能够访问它的域.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$response = array();
$response[0] = array(
'id' => '1',
'value1'=> 'value1',
'value2'=> 'value2'
);
echo json_encode($response);
?>
Run Code Online (Sandbox Code Playgroud)
以下是更多示例:如何绕过Access-Control-Allow-Origin?
Dan*_*Dan 10
返回带有HTTP 状态代码的JSON 响应的简单函数。
function json_response($data=null, $httpStatus=200)
{
header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();
}
Run Code Online (Sandbox Code Playgroud)
<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>
Run Code Online (Sandbox Code Playgroud)
小智 6
如果你想要 js 对象使用标头内容类型:
<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
如果您只想要 json :删除标头内容类型属性,只需编码和回显。
<?php
$data = /** whatever you're serializing **/;
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
小智 5
如上所述:
header('Content-Type: application/json');
Run Code Online (Sandbox Code Playgroud)
将工作。但请记住:
即使不使用此标头,Ajax都可以读取json,除非您的json包含一些HTML标记。在这种情况下,您需要将标头设置为application / json。
确保您的文件未使用UTF8-BOM编码。这种格式会在文件顶部添加一个字符,因此您的header()调用将失败。
| 归档时间: |
|
| 查看次数: |
952039 次 |
| 最近记录: |