HTML/Javascript: how to access JSON data loaded in a script tag with src set
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.
Loading a JSON file via a script tag
What you can do is set a global variable within your external file:
window.myJSON = { ... };
Then your other code can access that data via window.myJSON
.
I'm not sure how browsers parse .json
files so you may need to change the extension to .js
.
How can I read a JSON in the script-tag from JavaScript?
I would change the script declaration to this:
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
Note type and id fields. After that
var data = JSON.parse(document.getElementById('data').textContent);
will work just fine in all browsers.
The type="application/json"
is needed to prevent browser from parsing it while loading.
And the reason why we use textContent
instead of innerHTML
or innerText
to read the raw Json text is because innerHTML
tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText
won't grab the raw text and will instead look for human-visible text, whereas textContent
grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML
and innerText
are bad.
How to read json file correctly using only JavaScript
You can't load JSON through a script
element. Instead, in your script.js
, you can fetch
it:
fetch("data.json")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => {
// Use the data here, it's been parsed
})
.catch(error => {
// Handle/report error here
});
Parse JSON data inside from occurrence of script tag using SimpleHtmlDom - PHP
If you specify the index of the instance you want, you only get that element back and not a list, so the loop isn't required (in fact is the problem)...
$json = $html->find('script[type="application/ld+json"]',0);
echo $json->innertext;
Just for reference, the code from find()
...
// return nth-element or array
if (is_null($idx)) return $found;
else if ($idx<0) $idx = count($found) + $idx;
return (isset($found[$idx])) ? $found[$idx] : null;
Reading JSON from script in Javascript
The JSON isn't included. JSON is not a script and browsers have no idea what to do when you try to load it using a script element. All that script element is doing is sitting in the DOM. Therefore:
- Find the script element by its id
- Get the src attribute from it
- Use XMLHttpRequest to request the data
Related Topics
How to Prevent Buttons from Submitting Forms
Why Are Inline Event Handler Attributes a Bad Idea in Modern Semantic Html
Strip HTML from Text JavaScript
Using Html5/Canvas/JavaScript to Take In-Browser Screenshots
Unescape HTML Entities in JavaScript
How to Prevent Form from Being Submitted
How to Send Formdata Objects With Ajax-Requests in Jquery
Jquery/JavaScript to Replace Broken Images
How to Append to Innerhtml Without Destroying Descendants' Event Listeners
Difference Between ≪Script Src="Foo.Js"≫≪/Script≫ and ≪Script Src="Foo.Js"/≫
How Is the Default Submit Button on an HTML Form Determined
How to Properly Use Jspdf Library
(Html) Download a Pdf File Instead of Opening Them in Browser When Clicked