有人可以解释一下这种行为吗?
在这种情况下:
header("Content-type: text/html");
echo json_encode("error_101");
它有效。
在另一种情况下:
header("Content-type: application/json");
echo json_encode("error_101");
它不起作用(无限加载)。
但是,如果我将数组传递给 json_encode,它会以两种方式工作,因此这个问题仅存在于 json 值。
这似乎是一个错误!
最佳答案
json 文本中最外层的数据类型必须是数组或对象。
JSON Grammar
A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.
A JSON text is a serialized object or array.
JSON-text = object / array
—http://www.ietf.org/rfc/rfc4627.txt
如果您向 PHP 的 json_encode
函数传递一个字符串,那么它会将其输出为 JavaScript 编码字符串(而不是抛出错误)。我认为这是一个错误。
据推测,无论向该脚本发出 HTTP 请求,都会遇到无效 JSON 响应的问题,但对无效 HTML 具有更好的错误恢复能力。
关于php - 内容类型和 json_encode() 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933911/