Я написал функцию в PHP, которая получает информацию о продукте и желаемую информацию о калориях пользователя из базы данных и помещает всю информацию в массив. После этого он закодирован в JSON. Затем файл PHP используется в файле JavaScript .html, где он должен получить информацию, о которой я только что сказал из файла PHP, и выводит результаты линейной программы. Проблема заключается в том, что файл .html с JavaScript в нем возвращает ошибку в консоли и белой странице (скриншот).
Выход файла PHP показан на снимке экрана. Я взял вывод и вставил его в валидатор JSON, который показывает, что он действителен, поэтому я не вижу проблемы здесь.
Есть предложения? < /P>
php (часть) : < /p>
// 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();
?>
< /code>
javascript: < /p>
// 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
}
});
Я написал функцию в PHP, которая получает информацию о продукте и желаемую информацию о калориях пользователя из базы данных и помещает всю информацию в массив. После этого он закодирован в JSON. Затем файл PHP используется в файле JavaScript .html, где он должен получить информацию, о которой я только что сказал из файла PHP, и выводит результаты линейной программы. Проблема заключается в том, что файл .html с JavaScript в нем возвращает ошибку в консоли и белой странице (скриншот). Выход файла PHP показан на снимке экрана. Я взял вывод и вставил его в валидатор JSON, который показывает, что он действителен, поэтому я не вижу проблемы здесь. Есть предложения? < /P> php (часть) : < /p> [code] // 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);
// 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 } });