I am new to both three.js and javascript so this might be a very noob question.
I have a list of json objects in a file which contains data as following:
[
{ "x":x,"y":y,"z":z ,"r":r},
{ "x":x2,"y":y2,"z":z2 ,"r":r2},
{ "x":x3,"y":y3,"z":z 3,"r":r3}
]
And render it on screen.
Its exactly an example here: http://mrdoob.github.com/three.js/examples/webgl_materials2.html
except that sphere values I am reading from a file?
How do i tweak the example above that i read the values from this file instead of directly hardcoding these values in js?
Please help
THanks
If all you want to do is separate the data from your application logic, then you don't need to create a JSON file and load it via Ajax, you can just create another JavaScript file and put the data in there.
For example:
// myData.js
var myData = [
{ "x":x,"y":y,"z":z ,"r":r},
{ "x":x2,"y":y2,"z":z2 ,"r":r2},
// ...
];
// --------------
// myApplication.js
// Here goes the three.js code and you can access the data here, for example
alert(myData[0].x);
In your HTML file, you have to include the data file first, so that all following scripts have access to the myData variabe:
<script src="myData.js"></script>
<script src="myApplication.js"></script>
<!-- this works to: -->
<script>
alert(myData.length);
</script>
If you want to or have to load the file via Ajax, have a look at this question: How do I load a JSON object from a file with ajax?.
Related
I have this JSON file I generate in the server I want to make accessible on the client as the page is viewable. Basically what I want to achieve is:
I have the following tag declared in my html document:
<script id="test" type="application/json" src="http://myresources/stuf.json">
The file referred in its source has JSON data. As I've seen, data has been downloaded, just like it happens with the scripts.
Now, how do I access it in Javascript? I've tried accessing the script tag, with and without jQuery, using a multitude of methods to try to get my JSON data, but somehow this doesn't work. Getting its innerHTML would have worked had the json data been written inline in the script. Which it wasn't and isn't what I'm trying to achieve.
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
You can't load JSON like that, sorry.
I know you're thinking "why I can't I just use src here? I've seen stuff like this...":
<script id="myJson" type="application/json">
{
name: 'Foo'
}
</script>
<script type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(x.name); //Foo
});
</script>
... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.
You have a short list of options to load your JSON from a remote file:
Use $.get('your.json') or some other such AJAX method.
Write a file that sets a global variable to your json. (seems hokey).
Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
Consult a voodoo priest.
Final point:
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.
Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:
<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>
The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:
<script>var jsonData = <?php include('stuff.json');?>;</script>
The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.
It would appear this is not possible, or at least not supported.
From the HTML5 specification:
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.
While it's not currently possible with the script tag, it is possible with an iframe if it's from the same domain.
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
To use the above, simply replace the id and src attribute with what you need. The id (which we'll assume in this situation is equal to mySpecialId) will be used to store the data in window.jsonData["mySpecialId"].
In other words, for every iframe that has an id and uses the onload script will have that data synchronously loaded into the window.jsonData object under the id specified.
I did this for fun and to show that it's "possible' but I do not recommend that it be used.
Here is an alternative that uses a callback instead.
<script>
function someCallback(data){
/** do something with data */
console.log(data);
}
function jsonOnLoad(callback){
const raw = this.contentWindow.document.body.textContent.trim();
try {
const data = JSON.parse(raw);
/** do something with data */
callback(data);
}catch(e){
console.warn(e.message);
}
this.remove();
}
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
Tested in chrome and should work in firefox. Unsure about IE or Safari.
I agree with Ben. You cannot load/import the simple JSON file.
But if you absolutely want to do that and have flexibility to update json file, you can
my-json.js
var myJSON = {
id: "12ws",
name: "smith"
}
index.html
<head>
<script src="my-json.js"></script>
</head>
<body onload="document.getElementById('json-holder').innerHTML = JSON.stringify(myJSON);">
<div id="json-holder"></div>
</body>
place something like this in your script file json-content.js
var mainjson = { your json data}
then call it from script tag
<script src="json-content.js"></script>
then you can use it in next script
<script>
console.log(mainjson)
</script>
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
If you need to load JSON from another domain:
http://en.wikipedia.org/wiki/JSONP
However be aware of potential XSSI attacks:
https://www.scip.ch/en/?labs.20160414
If it's the same domain so just use Ajax.
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};
While not being supported, there is an common alternative to get json into javascript. You state that "remote json request" it is not an option but you may want to consider it since it may be the best solution there is.
If the src attribute was supported, it would be doing a remote json request, so I don't see why you would want to avoid that while actively seeking to do it in an almost same fashion.
Solution :
<script>
async function loadJson(){
const res = await fetch('content.json');
const json = await res.json();
}
loadJson();
</script>
Advantages
allows caching, make sure your hosting/server sets that up properly
on chrome, after profiling using the performance tab, I noticed that it has the smallest CPU footprint compared to : inline JS, inline JSON, external JS.
I'm new to programming, I'm trying to build a web app using nodejs/expressjs.
so basically on the post route, after some processing on backend it gives an array of object in result variable, I want to use this result variable data and construct a table in html file and send this table.html file as a response to client
the problem I'm encountering is how can I use this result variable to add element of table in html file dynamically (since array size changes everytime )
approach i was using
i created table.html and table.js that is linked with same html file.. but when table.html is send as a response that html file and table.js file is rendered on client side and not able to pass the result value that i get from server to that table.js file ( i get a document not defined error)
i tried to use EJS template .. how to create a function that used ejs variable to loop through array data and show table.. i'm unable to do
if anyone can help me to show result=[{name:'james', id:23},{name:'joe',id:35}]
to html file as response
main.js
app.post('/dataTbale',(req,res) => {
// after some processing i get array of obj that i store in result variable
const result=[{name:'james', id:23},{name:'joe',id:35}];
res.send('table.html);
})
table.html
<html>
<body>
<h2>table</h2>
<div id="show_table"></div>
<script src="table.js"></script>
</body>
</html>
table.js
const tableDiv=document.queryselector('#show_tabel');
result.forEach((obj) => { //<==== i want to pass that result data here.
tableDiv.innerHTML += result;
});
P.S just want to know if this works then i can create table
You might use a template engine like (ejs) or any other template engines to show the dynamic data that returns back from the server and for the case that you want to render the results in different page you should store the data in any kind of storages like local storage or database to be able to use it in different places.
I'm trying to create an online bookshop website and, since I don't have to fetch data from a database, I've thought about loading my book-objects from a JSON file.
What I should do is: loading the objects from the JSON file and building dynamically the pages (e.g. a page with a list of all the available books, another one with a search bar with filters and so on).
I've recently started to study HTML, CSS, JS (and Node.JS), so I'm not really sure about what I can actually do and what I can't.
I've read online that I could use JQuery in my HTML file to load the JSON from the URL, but still I was wondering: is there any chance that I can load the JSON content in my JS file (maybe through path and fs as in Node.JS) and use it like dynamic content (e.g. through .innerHTML)?
You don't need server side code for this.
Let's assume you have a JSON file called books.json in the same directory as your javascript file:
{
"books": [
{"title": "book1", "author": "author1"},
{"title": "book2", "author": "author2"}
]
}
And a index.html:
<div id="books"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="script.js"></script>
In your script.js, you can load the JSON like this with jQuery:
// global variable
var data;
$.get('books.json', function(d) {
data = JSON.parse(d);
// loop through all books
data.books.forEach(function(b) {
// now you can put every book in your <div>
$("#books").append(`<div><h2>${b.title}</h2><p>${b.author}</p></div>`);
});
});
The search function could go like this:
html:
<input id="input" /><button onclick="search()">search</button>
javascript:
function search() {
$("#books").html("");
let search = $("#input").val();
// filter the data
let filtered = $(data).filter(function (i,b){return b.title == search || b.author == search});
filtered.books.forEach(function(b) {
$("#books").append(`<div><h2>${b.title}</h2><p>${b.author}</p></div>`);
});
}
I'm using jade to do all my rendering, and I"m passing my data from my controller in node into my page template.
I want to add an object inline with javascript... I have a variable app in a js file, and I want to include more data into that app object. I have the following:
script(type="text/javascript")
app.stations = !{page_data.station_info}
Which I would want to output as
script(trype="text/javascript")
app.stations = [{my json object}]
But instead it's rendering like this:
<script type="text/javascript">
<app class="stations">= [my json object]
</app>
EDIT:
After an hour of research I figured it out: (you need to put a . after script
script.
app.stations = JSON STUFF
After an hour of research I was able to figure it out... You do script. and then write your javascript normally. See below
script.
app.stations = JSON STUFF
I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.