[英]Display BLOB image from db using JSON
我尝试使用JSON显示图像,但是我得到了
Uncaught SyntaxError:JSON输入意外结束
作为错误。 我尝试了很多方法,以多种方式来解决它,但失败了。 我可以显示文本(从没有图像的表(BLOB)中进行了测试),但是当我尝试使用包含图像的表时出现错误。
这是我的代码:
PHP-用于获取图像:
<?php header("Content-Type: application/json; charset=UTF-8"); //header('Content-Type:image/jpeg'); $obj = json_decode($_GET["x"], false); $conn = new mysqli("localhost", "abu", "aburefko159753", "btt"); $result = $conn->query("SELECT * FROM " . $obj->table . " LIMIT " . $obj->limit); $output = array(); $output = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($output); ?>
用于显示图像的HTML和JS代码:
<script> var obj, dbParam, xmlhttp; obj = { "table":"bestPlaces", "limit":4 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; console.log(this.responseText); var myObj = JSON.parse(this.responseText); document.getElementById("demo2").innerHTML = myObj[0].ID; console.log(myObj[0].ID); } }; xmlhttp.open("GET", "getPlaces.php?x=" + dbParam, true); xmlhttp.send(); </script>
<p id="test"></p> <p id="test2"></p>
当我使用另一个没有图像的表时,相同的代码可以正常工作,输出为:
[{"ID":"1","name":"test bez session","content":"abu test test"},
{"ID":"2","name":"test bez session","content":"abu test test"},
{"ID":"3","name":"test bez session","content":"test test 2"},
{"ID":"4","name":"test bez session","content":"abu juhu test"}
]
1个
但是当我将表与图像一起使用时会崩溃。 有什么帮助吗?
是否console.log(this.responseText);
显示完整的JSON输出?
我的猜测是您在二进制数据上遇到了json_encode或JSON.parse的麻烦。 尝试使用以下方法在base64中对其进行编码:
$output['imageCol'] = base64_encode($output['imageCol']);
echo json_encode($output);
其中imageCol
是BLOB列的名称,然后是JS:
var myObj = JSON.parse(this.responseText);
myObj.imageCol = atob(myObj.imageCol);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.