使用XHR调用PHP获取SQLite数据时遇SQLite3Result转字符串错误
问题根源与解决方法
这个错误的核心原因不是前端需要stringify,而是你的PHP代码直接把SQLite3Result对象输出给了前端——PHP没法把这个数据库结果对象直接转换成字符串,所以抛出了那个错误。你得先在PHP端把查询结果转换成前端能识别的格式(比如JSON),再返回给前端处理。
步骤1:修改PHP代码,将SQLite查询结果转为JSON
你需要遍历SQLite3Result对象,把每一行数据提取成数组,再用json_encode()转成JSON字符串输出,同时设置正确的响应头:
<?php // 连接数据库 $db = new SQLite3('your_database.db'); // 执行查询 $stmt = $db->query('SELECT * FROM your_table_name'); // 把查询结果转成关联数组 $results = []; while ($row = $stmt->fetchArray(SQLITE3_ASSOC)) { $results[] = $row; } // 设置响应类型为JSON,告诉前端这是JSON数据 header('Content-Type: application/json'); // 输出JSON字符串 echo json_encode($results); // 关闭数据库连接 $db->close(); ?>
步骤2:前端XHR处理JSON响应
现在后端返回的是标准JSON,你可以直接在前端解析并使用:
const xhr = new XMLHttpRequest(); xhr.open('GET', 'your_php_file.php', true); // 告诉XHR直接把响应解析成JSON对象 xhr.responseType = 'json'; xhr.onload = function() { if (this.status >= 200 && this.status < 300) { // 这里直接拿到解析好的JS数组/对象 console.log('查询结果:', this.response); // 比如遍历结果 this.response.forEach(row => { console.log(row.column_name); }); } else { console.error('请求失败:', this.statusText); } }; xhr.send();
为什么之前会报错?
当你在PHP中直接输出SQLite3Result对象(比如没处理就echo $stmt),PHP会尝试把对象转换成字符串,但SQLite3Result类没有实现字符串转换的逻辑,所以就抛出了Object of class SQLite3Result could not be converted to string错误——这跟前端的JSON.stringify没关系,前端根本没机会拿到正确的数据,因为后端已经输出错误信息了。
内容的提问来源于stack exchange,提问作者s89_
相关产品推荐
相关产品推荐

