How can I display json data on the html using script.js? - javascript

index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<body>
<div id="demo"></div>
<script type="module" src="./js/script.js"></script>
</body>
</html>
script.js:
import demo from './data.json'
document.getElementById("demo").innerHTML = demo;
console.log(demo)
Error in the console:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.
JSON data locates near script.js in the same directory
How can I display JSON data on the HTML using script.js?

Use JQuery.
<button onclick="showList()">Show List</button>
<script>
function showList(){
fetch("./data.json")
.then(response => response.json())
.then(data => createList(data));
}
function createList(data) {
//code to process here
}
</script>
My Source: https://www.tutorialstonight.com/display-json-data-in-html-page

You can display JSON data on the HTML using something like this, accessing the data from the imported ./data.json file (If the JSON data is located in the same JavaScript file, you can simply assign the data to a variable and access it from there.) and rendering it, your code is correct but need JSON.stringify(demo) the data.
For example, you can use the document.getElementById() method to select your with id="demo" and then set its innerHTML property to the JSON data.
const demo = {
"name": "John",
"age": 30,
"city": "New York"
};
const demoDiv = document.getElementById("demo");
demoDiv.innerHTML = JSON.stringify(demo);
<div id="demo"></div>
This will convert the JSON data to a string and display it
cheers

Related

could not load json data in d3 js

i am new in D3 JS. I would like to load json data from D3 js. Here, I am not sure if json is loaded. Here, non of message is appear. I want show html and json data ,
mydata.json
[
{"name":"Hira","age":35},
{"name":"Basu","age":26},
{"name":"Mukhia","age":30}
]
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
d3.json("./mydata.json", function(data) {
console.log(data);
});
</script>
</body>
</html>
Hope if you guys can give some hints.
here, I got a solution.
d3.json("./mydata.json").then(function(data){
console.log(data);
});
In new version we have to specify then function . In then function we have to make call back function.

Adding an external JavaScript file in NetBeans and linking with the index file

I have added a JavaScript file into my existing project and referred that in the HTML file. The file structure is shown as its in the attachment. After I run the program, the output does not display what it is supposed to be.
Is there anything wrong with my file tree (how I am adding file into the project) or I am not referring the script the in the correct way?
Here is how my program looks like:
index:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="newjavascript.js" type="text/javascript"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
.JS:
document.getElementById("demo").innerHTML = 7+9;
It seems to be everything is ok with your project structure and refererring to js file inside index.html. However, the demo paragraph does not display what you want because it can be just not loaded in the time when your newjavascript.js is executed. I think you can try to modify it in the following way:
window.onload = function () {
document.getElementById("demo").innerHTML = 7+9;
};
Using onload function of window object you wait until a page (including demo paragraph) is loaded - and after it change its content.

Include html in another html file [duplicate]

This question already has answers here:
Include another HTML file in a HTML file
(41 answers)
Closed 2 years ago.
I have a html "head" template and a navigation template that I want to include in all my other html files for my site.
I found this post:
Include another HTML file in a HTML file
And my question is... what if it's the header that I want to include?
So for example, I have the following file structure:
/var/www/includes/templates/header.html
navigation.html
header.html might look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Test Portal</title>
</head>
In a case like this, can I still follow the example in the other post where they create a div and populate the div via jquery?
Method 1:
I think it would be best way to include an html content/file into another html file using jQuery.
You can simply include the jQuery.js and load the HTML file using $("#DivContent").load("yourFile.html");
For example
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#DivContent").load("another_file.html");
});
</script>
</head>
<body>
<div id="DivContent"></div>
</body>
</html>
Method 2:
There are no such tags available to include the file but there are some third party methods available like this:
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="content.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
Method 3:
Some people also used server-side-includes (SSI):
<!--#include virtual="a.html" -->
Use <object> tag:
<object data="filename.html"></object>
I needed to include many files. So I created the following script:
<script>
$(function(){
$('[id$="-include"]').each(function (e){
$(this).load("includes\\" + $(this).attr("id").replace("-include", "") + ".html");
});
});
</script>
Use div, for example, to put a placeholder for the insertion.
<div id="example-include"></div>
Created folder "includes" for all files I needed to include. Created file "example.html".
It works with any number of includes. You just have to use the name convention and put all included files in the right folder.
Using HTML <iframe> tag.
I have faced similar problem , then I used
<*iframe* src = "b.html" height="*80px*" width="*500px*" > </*iframe*>
For anyone interested in a Web Component approach:
<html-include src="my-html.html"></html-include>
And the corresponding JS:
class HTMLInclude extends HTMLElement {
constructor() {
super();
this.innerHTML = "Loading...";
this.loadContent();
}
async loadContent() {
const source = this.getAttribute("src");
if (!source) {
throw new Error("No src attribute given.");
}
const response = await fetch(source);
if (response.status !== 200) {
throw new Error(`Could not load resource: ${source}`);
}
const content = await response.text();
this.innerHTML = content;
}
}
window.customElements.define("html-include", HTMLInclude);
Note that it is possible to do some nice things with a shadow DOM to make sure styling of loaded content does not influence the outer page.
The above code is pretty "modern" JS and you might not want to use the above code directly without some polyfills/babel transpilation.
This is similar to another custom tag solution, but this one uses the text between the opening and closing tags as the include path/url. The other solution uses the src attribute instead.
<html-include> ./partials/toolbar.html </html-include>
The element implementation's a little trickier:
# -- ./js/html-include.js --
class HTMLInclude extends HTMLElement {
constructor(src) {
super();
this.attachShadow({mode: "open"});
if (src) {
this.textContent = src;
}
setTimeout(() => this._load());
}
async _load() {
let src = this.textContent.trim();
if (!src) {
throw new Error("URL missing between <html-import> tags.");
}
let rsp = await fetch(src);
if (rsp.status != 200) {
throw new Error(`Failed to load file (${src}) for <html-import>.`);
}
this.shadowRoot.innerHTML = await rsp.text();
}
}
customElements.define("html-include", HTMLInclude);
The setTimeout() was necessary because this.textContent, if accessed too early, can include all the preceding text of the page (seen on Chrome/Chromium). Deferring the access fixes that.
This is what it looks like incorporated in a page:
<html>
<head>
<link rel="stylesheet" href="./css/index.css">
<script type="text/javascript" src="./js/html-include.js"></script>
</head>
<body>
<html-include> ./partials/toolbar.html </html-include>
<html-include> ./partials/side-menu.html </html-include>
<html-include> ./partials/statusbar.html </html-include>
</body>
</html>
CSS styles should be properly applied to the newly imported HTML.
This element can also be created from JS by passing it the URL to the import file.
let wgthost = document.getElementById("tgt");
wgthost.appendChild(new HTMLInclude("./partials/mywidget.html"));

How to grab the "response" of the server using JQuery?

Please have a look at the below code.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//cdnjs.cloudflare.com/ajax/libs/annyang/1.1.0/annyang.min.js"></script>
<script>
if (annyang) {
// Let's define our first command. First the text we expect, and then the function it should call
var commands = {
'hello': function() {
alert("Hello!");
}
};
// Add our commands to annyang
annyang.addCommands(commands);
// Start listening. You can call this here, or attach this call to an event, button, etc.
// annyang.start();
}
</script>
</head>
<body>
<div>TODO write content</div>
<button onclick="annyang.start();">Start</button>
</body>
</html>
The JavaScript code sends the data to a external server and get the response. The imported JS file can be found from here - https://github.com/TalAter/annyang
My question is, how can I view the "response" which I get from the server?
To see the results returned in the console, turn on debug mode by adding this:
annyang.debug();
Alternatively, to capture all recognized text in a function, simply add a catch-all function
annyang.addCommands({
'*transcript': function(transcript) {
console.log(transcript);
}
});
P.S. I think you want to uncomment your start() command.

how to show json data from web service

I have that link http://api.openweathermap.org/data/2.5/weather?q=Andorra+la+Vella that shows on the browser a json with all the values, so I need to pick only the wind, and the temp, but I don't know how to extract it, how to do that?
I thougt in add a callback after "Andorra+la+Vella"&callback=myFunction
And develop a code on javascript to get the values that I need, but I do it and something goes wrong, that's a simple test to try this little application and then i add it to my web:
<!DOCTYPE HTML>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Test tiempo andorra</title>
<script type="text/javascript">
function showTime(obj) {
var dadIp=document.getElementById('time');
dadIp.innerHTML+=obj.sunset.wind.speed;
}
</script>
</head>
<body>
<div id="time">
<h1>Test of Time in Andorra</h1>
</div>
<script type="text/javascript" src="http://api.openweathermap.org/data/2.5/weather?q=Andorra+la+Vella&callback=showTime"></script>
</body>
</html>
Look at your JavaScript error console.
Uncaught TypeError: Cannot read property 'wind' of undefined
Then look at the JSON source.
obj.sunset doesn't exist. obj.sys.sunset does.
obj.sunset.wind doesn't exist. obj.wind does.
See a live example when the correct object paths are used.
This way for example:
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;
In case if you need parse DateTime I advise to use moment.js library.

Categories

Resources