[英]Unexpected token 'o', "[object Obj"... is not a valid JSON
I have written a function in PHP which takes product information and user's desired calories information from a database and puts all of the information in an array.我在 PHP 中写了一个 function,它从数据库中获取产品信息和用户所需的卡路里信息,并将所有信息放入一个数组中。 Afterwards it's encoded in JSON. Then the PHP file is used in a Javascript.html file where it should take the information I just said about from the PHP file and outputs the linear program results.
然后在JSON中编码。然后PHP文件在Javascript.html文件中使用,它应该从PHP文件中提取我刚才说的信息并输出线性程序结果。 The problem is that the.html file with Javascript in it returns an error in the console and a white page (screenshot).
问题是其中包含 Javascript 的 .html 文件在控制台和白页(屏幕截图)中返回错误。 The PHP file output is shown in the screenshot.
屏幕截图中显示了 PHP 文件 output。 I took the output and pasted it in a JSON validator, which shows that it's valid, so I don't see the issue here.
我把 output 粘贴到 JSON 验证器中,这表明它是有效的,所以我看不到这里的问题。 Any suggestions?
有什么建议么?
PHP(part): 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: 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>
The parameter passed to the success
callback in jQuery's ajax
method has already been parsed . jQuery的
ajax
方法中传递给success
回调的参数已经解析过了。 It is not the string of JSON returned by the PHP, it is the result of reading that string of JSON into an ordinary JS object.它不是PHP返回的JSON的字符串,它是将JSON的字符串读入一个普通的JS object的结果。
In short, JSON.parse
has already been run before it gets to your code.简而言之,
JSON.parse
在到达您的代码之前已经运行。
So instead of this:所以不是这个:
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;
// ...
You just want this:你只想要这个:
success: function(data) {
// The response data is an object, from which we can get the products array and user's desired calories
products = data.products;
// ...
The reason you get the error you do is that JSON.parse
expects a string (a string of JSON data), but you're passing it an object (the one jQuery has passed you).你得到你做的错误的原因是
JSON.parse
需要一个字符串(一个字符串 JSON 数据),但你传递给它一个 object(一个 jQuery 已经传递给你)。 JavaScript "helpfully" turns the object into the string '[Object object]'
, and passes it to JSON.parse
. JavaScript “有用地”将 object 转换为字符串
'[Object object]'
,并将其传递给JSON.parse
。
you need to stringify the JSON before parsing, something like:您需要在解析之前对 JSON 进行字符串化,例如:
JSON.parse(JSON.stringify(response)); JSON.parse(JSON.stringify(响应));
Best regards,最好的祝福,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.