PHP生成JSON在JS解析报错:Unexpected token 'o' 求助
问题描述
我编写了一段PHP函数,从数据库中获取商品信息与用户期望的热量数据并存入数组,随后将其编码为JSON格式输出。在包含JavaScript的HTML文件中,我通过AJAX请求该PHP文件,期望获取数据后输出线性规划计算结果,但页面显示空白,控制台报错:Unexpected token 'o', "[object Obj"... is not a valid JSON。
我已将PHP输出内容放入JSON验证工具,确认格式合法,无法定位问题,恳请提供排查建议。
PHP部分代码
// Add the product data to the products array $products[] = [ 'name' => $productRow['product_name'], 'price' => $price, 'calories' => $energyRow['energy_value'], 'UserCalories' => $userCaloriesRow['calories'], ]; } // Output the products array as a JSON string header('Content-Type: application/json'); echo json_encode($products, JSON_UNESCAPED_UNICODE); $mysql->close(); return $products; } fetchProductsFromDatabase(); ?>
JavaScript代码
<script src="https://unpkg.com/javascript-lp-solver@0.4.24/prod/solver.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Initialize the products and calories arrays var products = []; var calories = 0; // Make an AJAX request to the PHP script that fetches the products and user's desired calories from the database $.ajax({ url: 'fetchProductsFromDatabase.php', success: function(response) { // The response is a JSON object, so we need to parse it to get the products array and user's desired calories var data = JSON.parse(response); products = data.products; // Set up the linear programming problem var lp = new LinearProgramming(0, LinearProgramming.MAXIMIZE); // Set up the constraints var caloriesConstraint = {}; for (var i = 0; i < products.length; i++) { caloriesConstraint[i] = products[i]['calories']; } lp.addConstraint(caloriesConstraint, LinearProgramming.EQUAL, calories); // Set up the objective function var priceObjective = {}; for (var i = 0; i < products.length; i++) { priceObjective[i] = products[i]['price']; } lp.setObjective(priceObjective); // Solve the linear program var result = lp.solve(); // Print the results for (var i = 0; i < products.length; i++) { console.log(products[i]['name'] + ': ' + result[i]); } console.log('Total cost: ' + lp.getObjectiveValue()); }, error: function(jqXHR, textStatus, errorThrown) { // There was an error with the request console.log(jqXHR.responseText); // Output the response from the server console.log(textStatus); // Output the error type console.log(errorThrown); // Output the exception object, if available } }); </script>
(注:已验证PHP输出的JSON格式合法)
排查建议
- 停止重复解析JSON:jQuery的
$.ajax会根据PHP返回的Content-Type: application/json自动将响应解析为JavaScript对象,此时再调用JSON.parse(response)会把对象转为字符串"[object Object]",直接触发报错。删除JSON.parse步骤,直接使用response即可。 - 修正数据结构访问逻辑:你的PHP输出的是一个数组(每个元素包含
UserCalories字段),而非带products属性的对象。JS里products = data.products会得到undefined,应改为products = response,同时提取用户热量值,比如:// 若所有元素的UserCalories值一致,取第一个元素的对应值 calories = response[0].UserCalories; - 清除PHP多余输出:即使JSON格式合法,PHP文件可能在JSON前后输出了空格、换行或隐性错误提示。在PHP开头加入
ob_start(),输出JSON前执行ob_clean()清空缓冲区,输出后用exit()终止脚本,避免后续代码生成多余内容:ob_start(); // ... 数据库操作代码 ... header('Content-Type: application/json'); ob_clean(); echo json_encode($products, JSON_UNESCAPED_UNICODE); exit; - 确认AJAX接收的实际内容:在
success回调开头添加console.log(typeof response, response),查看返回值的类型和结构是否符合预期。 - 核对线性规划库API:确认
LinearProgramming类的初始化和调用方式是否正确,部分库的API可能和你当前写法不符,需核对库的使用文档。
内容的提问来源于stack exchange,提问作者Muffin
相关产品推荐
相关产品推荐

