I try to pass a JSON as String from my Spring Controller to the React Frontend.
JSON:
{
"name": ".",
"size": 0,
"children": [
{
"name": "setup.bat",
"size": 6,
"children": []
},
{
"name": "src",
"size": 0,
"children": [
{
"name": "main",
"size": 0,
"children": [
{
"name": "java",
"size": 0,
"children": [
...
I try it with Thymeleaf and the console output on my site worked:
index.html
$( document ).ready(function() {
var jsondata = /*[[${jsondata}]]*/;
console.debug(jsondata);
});
but now i try to used it in react I get an error:
app.js:
class App extends Component {
render() {
return(
<div>
{jsondata}
</div>
)
}
}
Uncaught ReferenceError: jsondata is not defined
What is the Problem in React ?
Set and access the JSON on directly on the window object.
window.jsondata = /*[[${jsondata}]]*/;
class App extends Component {
render() {
return(
<div>
{window.jsondata}
</div>
)
}
}
Solution:
I can use the Javascript var with my React code, but the Problem was in my html file. I make a wrong order of the scripts.
If i use the React bundle at the end it works:
index.html:
<script th:inline="javascript">
var jsondata = /*[[${jsonHierarchy}]]*/;
console.log(jsondata);
</script>
<script src="/bundle.js"></script>
Related
I'm trying to display JSON data on my webpage by using the v-for function in Vue.js and Axios to get the data. Below is my code and an example of the JSON data i'm trying to use.
I have kept the JSON data URL out on purpose as it's private, which is why i've provided an example of the data structure.
I can print the entire data set to my page, as it appears below but if i use my code below to print specific parts of data, like the id or name, that's when i get nothing on the page.
<div id="root">
<p v-for="item in items">{{ item.name }}</p>
</div>
<script>
var app = new Vue({
el: '#root',
data: {
items: []
},
mounted() {
axios.get("...")
.then(response => {this.items = response.data.data})
}
});
</script>
JSON data example:
json
{
"current_page": 1,
"data": [
{
"id": "83",
"name": "Name1",
},
{
"id": "78",
"name": "Name2",
},
{
"id": "720",
"name": "Name3",
},
{
"id": "707",
"name": "Name4",
},
{
"id": "708",
"name": "Name5",
}
],
"from": 1,
"prev_page_url": null,
"to": 20,
"total": 42
}
looking at the code everything looks ok, but i have an example in the application i am working on and i've noticed that your items array should contain response.data.data.data wich is verbose but you can work on that later
I'm working with Symfony 3, Angular JS and Twig. My problem comes when I try to generate a JSON in a view(html.twig).
My Model (MongoDB)
{
"_id" : ObjectId("5a1feb783e06fa060c0076b2"),
"contenido" : [
[
{
"type": "item",
"name": "Foo",
"id": 5
},
{
"type": "item",
"name": "Bar",
"id": 6
}
]
]
}
My Controller:
class Controlador extends Controller
{
// This method retrieve data (Document) from MongoDB
public function renderizar(Request $request)
{
...
$repository= $this->get('doctrine_mongodb')
->getManager()
->getRepository('AppBundle:Class');
$object = $repository->find('5a1feb783e06dfa060c0076b2');
$contenido = json_encode($object->getContenido());
$contenidoB = htmlentities($contenido);
$contenidoC = html_entity_decode($contenidoB);
$contenidoDef = json_decode($contenidoC);
return $this->render('view.html.twig', 'contenido' => $contenidoDef));
}
}
I want to generate that JSON in the view (inside the AngularJS's controller) in order to render a drag and drop panel from AngularJS.
My view
{% block body %}
<!doctype html>
<html >
<head>
<script>
angular.module("app").controller("NestedListsDemoController", function($scope)
{
$scope.models = {
dropzones: {
"A": [
{
"type": "container",
"name": "container",
"id": 4,
"columns": [
[
{
"type": "item",
"name": "Foo",
"id": 5
},
{
"type": "item",
"name": "Bar",
"id": 6
}
]
]
}
]
}
};
});
</script>
...
{% endblock %}
The Angular's controller doenst recognize the JSON in view if I use variable that contains that JSON.
dropzones: {
...
"A": {{ contenido|raw }}
}
or
dropzones: {
...
"A": {{ contenido }}
}
However, If I write the JSON in the view, it works. But I need to put the content from that variable. Any idea? Could anyone help me?
I solved the problem changing the string I would received in controller. When I retreive the document from MongoDB (I don't know why) comes with an extra double [ ] . Then, the drag and drop panel didn't recognize that JSON format...
To solve, first I removed them in controller, secondly I generated the JSON in the view as follows:
dropzones: {
"A": [ {{ contenido|raw }} ]
}
That's all, it works for me.
Use this:
dropzones = {{ contenido|json_encode|raw }};
I have a json object which contains html tags in it.I have understood the disadvantage of using dangerouslySetInnerHTML and trying to use parse/stringify instead of it.But I could't convert the object to html tags.I'm not allowed to use any other react packages. So, is there any solution ?
[
{
"category": "Chapter",
"results": [
{
"content": "that <em>cultural</em> tool you don’t do a good job of it. From this perspective, <em>culture</em>",
"id": "4c00-b7f6-d6e0e252ae9e"
},
{
"content": "sample <em>culture</em>",
"id": "4c00-b7f6-d6e0e252ae9e"
}
]
},
{
"category": "Learning Objectives",
"results": [
{
"content": " <em>culture</em> is a communication.",
"id": "4c00-b7f6-d6e0e252ae9e"
},
{
"content": "sample <em>culture</em> which",
"id": "4c00-b7f6-d6e0e252ae9e"
}
]
}
]
import React from 'react';
import PropTypes from 'prop-types';
const Result = ({ data, onSearchResultClick }) => (<div >
{
data.map((category, index) => (
<div key={index}>
<div key={index}>{category.category}</div>
<hr />
<div className="searchShowData" >
{
category.results.map((result, resultIndex) => (
<p
key={resultIndex}
dangerouslySetInnerHTML={{ __html: (result.content) }}
onClick={() => onResultClick(result.id, result.type)}
/>
))
}
</div>
</div>
))
}
</div>);
Result.propTypes = {
data: PropTypes.array.isRequired,
onSearchResultClick: PropTypes.func.isRequired
};
export default Result;
file snapshot_report_js.js:
require([
"dojo/dom",
"dojo/json",
"dojo/store/Memory",
"dijit/tree/ObjectStoreModel",
"dijit/Tree",
"dojo/text!http://localhost:8080/dojo/json_data/snapshot.json",
"dojo/domReady!",
"dojo/_base/json"
], function(dom, json, Memory, ObjectStoreModel, Tree, small){
var stringfied_content = JSON.stringify(small)
var json_parsed_data = JSON.parse(stringfied_content, true)
var json_data = dojo.toJson(json_parsed_data);
// set up the store to get the tree data
var json_store = new Memory({
data: [ json_data ],
getChildren: function(object){
return object.children || [];
}
});
// Create the model
var snapshot_treeModel = new ObjectStoreModel({
store: json_store,
query: {id: 'snapshot'}
});
var snapshot_tree = new dijit.Tree({
model: snapshot_treeModel
}, 'div_snapshot_tree');
snapshot_tree.startup();
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Snapshot</title>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">
<!-- load Dojo -->
<script src="dojo/dojo.js" data-dojo-config="async: true"></script>
<script src="js/snapshot_report_js.js"></script>
</head>
<body class="claro">
<div id="div_snapshot_tree"></div>
</body>
</html>
JSON file:
{
"snapshot_metadata": {
"report_end_at": "2017-10-11 02:03:36",
"environment_name": "DVINST",
"report_start_at": "2017-10-11 01:55:42"
},
"versions": [
{
"id": "version_001",
"instances": [
{
"instance_name": "instance1",
"instance_create_date": "2017-09-18 00:17:52",
"connected_site_count": 4,
"admin_server": "t3://tserver:18300",
"instance_id": 2411,
"instance_type": "OSVC",
"instance_created_by": "None",
"site_capacity": 2,
"sites": [
{
"site_db_id": 395,
"site_name": "zzzz_178",
"site_users": "uc1,uc2,uc3",
"site_id": 89492,
"site_owner": "owner1",
"site_db_name": "site_server2"
},
{
"site_db_id": 395,
"site_name": "site2",
"site_users": "u1, u2, u3",
"site_id": 90447,
"site_owner": "u2",
"site_db_name": "site_server3"
}
]
}
]
}
],
"servers": [
{
"status": null,
"server_id": 13,
"server_name": "db1",
"server_type": "database",
"mount_points": [],
"sites": [],
"db_connections_count": 6,
"health": null,
"admin_servers": null,
"db_sites_connected_count": null
}
]
}
Error on console:
dojo.js:8 Uncaught Error: dijit.tree.ObjectStoreModel: root query
returned 0 items, but must return exactly one at Object.
(ObjectStoreModel.js.uncompressed.js:86) at dojo.js:8 at when
(dojo.js:8) at Object.getRoot
(ObjectStoreModel.js.uncompressed.js:82) at Object._load
(Tree.js.uncompressed.js:897) at Object.postCreate
(Tree.js.uncompressed.js:844) at Object.create
(_WidgetBase.js.uncompressed.js:453) at Object.postscript
(_WidgetBase.js.uncompressed.js:366) at new (dojo.js:8)
at snapshot_report_js.js:178
I don't see anything wrong here, can anybody help?
At first glance your ObjectStoreModel is trying to find root object for tree and as you specified it should have property id equals to snapshot; nothing in your JSON is matching that query.
Secondly, JSON data should bring tree-structured content while your JSON is unstructured; see ObjectStoreModel example how tree data looks like. If you have custom data structure then you need to transform it to be consumed by tree widget thru its model.
making first attempt to master Ember.js atm. I'm trying to make a simple CMS, but for some reason I have a problem with getting any data from json displayed. I've already switched from Fixture to RESTAdapter, but I am still stuck with
Error: assertion failed: Your server returned a hash with the key timestamp but you have no mapping for it.
Here's my js code:
App.Store = DS.Store.extend(
{
revision:12,
adapter: 'DS.RESTAdapter'
}
);
App.Menucategory = DS.Model.extend({
timestamp: DS.attr('number'),
status: DS.attr('string')
});
App.MenucategoryRoute = Ember.Route.extend({
model: function() {
return App.Menucategory.find();
}
});
DS.RESTAdapter.reopen({
url: <my url>
});
DS.RESTAdapter.configure("plurals", {
menucategory: "menucategory"
});
Trying to access it with:
<script type="text/x-handlebars" id="menucategory">
{{#each model}}
{{data}}
{{/each}}
</script>
My json structure:
{
"timestamp": 1366106783,
"status": "OK",
"data": [
{
"name": "starters",
"id": 1
},
{
"name": "main dishes",
"id": 2
}]}
Thank you in advance for any help you can provide.
By default the RESTAdapter expects your API to be in a specific format, which your API doesn't conform to, if you can modify your API, you need to get it to return in this format, otherwise you'll need to customize the adapter.
Expected Format (based on your JSON):
{
"menucategory": [
{
"name": "starters",
"id": 1
},
{
"name": "main dishes",
"id": 2
}
],
"meta": {
"timestamp": 1366106783,
"status": "OK",
}
}