简体   繁体   English

意外的标记 'o',“[object Obj”... 不是有效的 JSON

[英]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,最好的祝福,

意外标记 '&lt;', "<div id="text_translate"><p> 我是 Reactjs 的初学者和 StackOverflow 的新手。 实际上,我正在尝试将数据从后端传递到前端。 但不是从后端 url 获取 JSON 数据,而是从前端的 index.html 获取数据。 我的后端是nodejs。 基本上,我想从后端获取 JSON 数据并将数据发布到前端的控制台中。 但我得到这个SyntaxError: Unexpected token '&lt;', "&lt;.DOCTYPE "... is not valid JSON谁能帮我解决这个问题。 <a href="/questions/tagged/reactjs" class="post-tag" title="显示标记为“reactjs”的问题" aria-label="show questions tagged 'reactjs'" rel="nofollow noreferrer" aria-labelledby="reactjs-container">reactjs</a> <a href="/questions/tagged/nodejs" class="post-tag" title="显示标记为“nodejs”的问题" aria-label="show questions tagged 'nodejs'" rel="nofollow noreferrer" aria-labelledby="nodejs-container">nodejs</a></p><p> <strong>前端代码</strong></p><pre>App.js import React from 'react'; import {useState, useEffect} from 'react'; import {getOrder} from './ApiCalls.js' function App() { const[values, setValues]=useState({ amount:0, orderId:'' }) const{amount, orderId}=values useEffect(() =&gt; { createorder() }, []) const createorder=()=&gt;{ getOrder().then(response=&gt;console.log(response)) } const showRazorPay=()=&gt;{ const form=document.createElement('form') form.setAttribute('action',`${process.env.REACT_APP_BACKEND}/payment/callback`); form.setAttribute('method',"POST"); const script=document.createElement("script"); script.src= "https://checkout.razorpay.com/v1/checkout.js"; script.setAttribute("data-key",process.env.REACT_APP_DATA_KEY); script.setAttribute("data-amount", amount); script.setAttribute("data-prefill.contact","9561315545"); script.setAttribute("data-order_id", orderId); script.setAttribute("data-prefill.name", "Priyanka Chaudhari"); script.setAttribute("data-image", `${process.env.REACT_APP_BACKEND}/logo`) script.setAttribute("data-buttontext","Donate Now;"). document.body;appendChild(form). form;appendChild(script). const input= document;createElement("input"). input;type="hidden". input;custom="Hidden Element"; } return ( &lt;div&gt; &lt;/div&gt; ); } export default App;</pre><pre> ApiCalls.js export const getOrder=()=&gt;{ return fetch(`${process.env.REACT_APP_BACKEND}/createorder`,{ method: "GET", headers: { 'Content-Type':'application/json' } }).then(response=&gt;response.json()).catch((err)=&gt;console.log(err)) }</pre><p> <strong>后端代码</strong></p><pre>App.js const express=require('express') const bodyParser=require('body-parser') const cors=require('cors') const app=express() const PaymentRoute=require('./PaymentRoute') app.use(bodyParser.json()) app.use(cors()) app.use('/api',PaymentRoute); app.listen(5000,()=&gt;{ console.log(`App is running at 5000 port`) })</pre><pre> PaymentRoute.js const express=require('express') const router=express.Router() const{CreateOrder,paymentCallback,getLogo}=require('./PaymentController') router.get('/createorder',CreateOrder); router.post('/payment/callback',paymentCallback) router.get('/logo',getLogo) module.exports=router;</pre><pre> PaymentController.js require('dotenv').config() const Razorpay=require('razorpay') const uniqueId=require('uniqid') const path=require('path') var instance = new Razorpay({ key_id: process.env.KEY_ID, key_secret: process.env.SECRET_KEY }) // instance.payments.fetch(paymentId) exports.CreateOrder=(req,res)=&gt;{ var options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: uniqueId() }; instance.orders.create(options, function(err, order) { if(err){ return res.status(500).json({ error:err }) } res.json(order) }); } exports.paymentCallback=(req,res)=&gt;{ } exports.getLogo=(req,res)=&gt;{ res.sendFile(path.join(__dirname,'donate-image.png')) }</pre></div> - Unexpected token '<', "<!DOCTYPE "... is not valid JSON

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 API object 转为字符串 - JSON 中的意外令牌 o - API object turns to string - Unexpected token o in JSON 在位置1的JSON中出现意外的令牌o - Unexpected token o in JSON at position 1 合并两个有效的json对象时出现意外的令牌错误 - Unexpected token error when combining two valid json object 意外标记 '&lt;', "<div id="text_translate"><p> 我是 Reactjs 的初学者和 StackOverflow 的新手。 实际上,我正在尝试将数据从后端传递到前端。 但不是从后端 url 获取 JSON 数据,而是从前端的 index.html 获取数据。 我的后端是nodejs。 基本上,我想从后端获取 JSON 数据并将数据发布到前端的控制台中。 但我得到这个SyntaxError: Unexpected token '&lt;', "&lt;.DOCTYPE "... is not valid JSON谁能帮我解决这个问题。 <a href="/questions/tagged/reactjs" class="post-tag" title="显示标记为“reactjs”的问题" aria-label="show questions tagged 'reactjs'" rel="nofollow noreferrer" aria-labelledby="reactjs-container">reactjs</a> <a href="/questions/tagged/nodejs" class="post-tag" title="显示标记为“nodejs”的问题" aria-label="show questions tagged 'nodejs'" rel="nofollow noreferrer" aria-labelledby="nodejs-container">nodejs</a></p><p> <strong>前端代码</strong></p><pre>App.js import React from 'react'; import {useState, useEffect} from 'react'; import {getOrder} from './ApiCalls.js' function App() { const[values, setValues]=useState({ amount:0, orderId:'' }) const{amount, orderId}=values useEffect(() =&gt; { createorder() }, []) const createorder=()=&gt;{ getOrder().then(response=&gt;console.log(response)) } const showRazorPay=()=&gt;{ const form=document.createElement('form') form.setAttribute('action',`${process.env.REACT_APP_BACKEND}/payment/callback`); form.setAttribute('method',"POST"); const script=document.createElement("script"); script.src= "https://checkout.razorpay.com/v1/checkout.js"; script.setAttribute("data-key",process.env.REACT_APP_DATA_KEY); script.setAttribute("data-amount", amount); script.setAttribute("data-prefill.contact","9561315545"); script.setAttribute("data-order_id", orderId); script.setAttribute("data-prefill.name", "Priyanka Chaudhari"); script.setAttribute("data-image", `${process.env.REACT_APP_BACKEND}/logo`) script.setAttribute("data-buttontext","Donate Now;"). document.body;appendChild(form). form;appendChild(script). const input= document;createElement("input"). input;type="hidden". input;custom="Hidden Element"; } return ( &lt;div&gt; &lt;/div&gt; ); } export default App;</pre><pre> ApiCalls.js export const getOrder=()=&gt;{ return fetch(`${process.env.REACT_APP_BACKEND}/createorder`,{ method: "GET", headers: { 'Content-Type':'application/json' } }).then(response=&gt;response.json()).catch((err)=&gt;console.log(err)) }</pre><p> <strong>后端代码</strong></p><pre>App.js const express=require('express') const bodyParser=require('body-parser') const cors=require('cors') const app=express() const PaymentRoute=require('./PaymentRoute') app.use(bodyParser.json()) app.use(cors()) app.use('/api',PaymentRoute); app.listen(5000,()=&gt;{ console.log(`App is running at 5000 port`) })</pre><pre> PaymentRoute.js const express=require('express') const router=express.Router() const{CreateOrder,paymentCallback,getLogo}=require('./PaymentController') router.get('/createorder',CreateOrder); router.post('/payment/callback',paymentCallback) router.get('/logo',getLogo) module.exports=router;</pre><pre> PaymentController.js require('dotenv').config() const Razorpay=require('razorpay') const uniqueId=require('uniqid') const path=require('path') var instance = new Razorpay({ key_id: process.env.KEY_ID, key_secret: process.env.SECRET_KEY }) // instance.payments.fetch(paymentId) exports.CreateOrder=(req,res)=&gt;{ var options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: uniqueId() }; instance.orders.create(options, function(err, order) { if(err){ return res.status(500).json({ error:err }) } res.json(order) }); } exports.paymentCallback=(req,res)=&gt;{ } exports.getLogo=(req,res)=&gt;{ res.sendFile(path.join(__dirname,'donate-image.png')) }</pre></div> - Unexpected token '<', "<!DOCTYPE "... is not valid JSON 未捕获到的SyntaxError:JSON中位置1处的意外令牌o - Uncaught SyntaxError: Unexpected token o in JSON at position 1 JSON + Node.js - 意外的令牌o - JSON+Node.js - Unexpected token o SyntaxError:JSON中位置1 EXPRESS处的意外令牌o - SyntaxError: Unexpected token o in JSON at position 1 EXPRESS $ .parseJSON“在位置1的JSON中出现意外令牌o”问题 - “Unexpected token o in JSON at position 1” Issue with $.parseJSON 语法错误:JSON 中的意外标记 o 在 position 1 - SyntaxError: Unexpected token o in JSON at position 1 与JSON相关的错误:意外的令牌o - JSON related error: Unexpected token o
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM