我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
我想从PHP脚本返回JSON。
我只是重复结果吗?我必须设置内容类型头吗?
当前回答
设置访问安全性也很好——只需将*替换为您希望能够访问它的域。
<?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);
?>
这里有更多的例子:如何绕过Access-Control-Allow-Origin?
其他回答
如果你查询一个数据库,需要JSON格式的结果集,可以这样做:
<?php
$db = mysqli_connect("localhost","root","","mylogs");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
?>
有关使用jQuery解析结果的帮助,请参阅本教程。
如上所述:
header('Content-Type: application/json');
会完成这项工作。但请记住:
即使没有使用这个报头,Ajax读取json也没有问题,除非您的json包含一些HTML标记。在这种情况下,您需要将头文件设置为application/json。 确保您的文件不是用UTF8-BOM编码的。这种格式在文件顶部添加了一个字符,因此header()调用将失败。
你问题的答案在这里,
它说。
JSON文本的MIME媒体类型为 application / json。
所以如果你设置标题为那种类型,并输出你的JSON字符串,它应该工作。
这个问题有很多答案,但没有一个涵盖了返回干净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();
}
引用:
response_remove
ob_clean
JSON内容类型
HTTP规范
http_response_code
json_encode
如果你想要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);