我在資料庫中有一個 json 物件:
{
"ui": {},
"title": "Hola mundo 2",
"values": {},
"properties": {},
"description": "descripcion"
}
在 Laravel 控制器中,我將資料發送到視圖:
$surveyData = Empresa::find($empresa_id)->survey;
return view('surveys.edit')->with('surveyData', json_encode($surveyData));
在 Laravel Blade 中,我將資料附加到一個 div 中:
<div id="poll" data-survey=@json($surveyData)></div>
在 React 中,我獲取資料并保存在 oldData 變數中:
const oldData = document.querySelector("#poll").dataset.survey
問題是我在 React 中收到 JSON.parse 錯誤,因為該 JSON 在 Laravel 視圖 DOM 中以以下 unicode 格式列印:
<div id="poll" data-survey="\u0022{\\\u0022ui\\\u0022: {}, \\\u0022title\\\u0022: \\\u0022Hola mundo 2\\\u0022, \\\u0022values\\\u0022: {}, \\\u0022properties\\\u0022: {}, \\\u0022description\\\u0022: \\\u0022descripcion\\\u0022}\u0022"></div>
當我在 React 中決議那個 json 時:
JSON.parse(oldData)
我收到此錯誤:
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
我真的不知道錯誤在哪里或還能做什么。
uj5u.com熱心網友回復:
您似乎對您的 JSON 資料進行了雙重編碼:
json_encode($surveyData)然后@json($surveyData)
更改
return view('surveys.edit')->with('surveyData', json_encode($surveyData));
到
return view('surveys.edit')->with('surveyData', $surveyData);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338817.html
標籤:javascript php 反应 json 拉拉维尔
上一篇:將UnityJsonUtility與包含陣列的類一起使用
下一篇:搜索具有特定值的特定鍵的物件陣列
