I have a large file format "json". I need to use this information when you open the page in a browser. the only solution - is to place the data into a variable in the ".js" file, but it turns out 5000 lines. Maybe there is an option to read data? I open the page in folder
The JSON.parse() method parses a JSON string, constructing the
JavaScript value or object described by the string.
-MDN
If you need those objects to render out your webpage / webapp you're going to have to get them to the browser. Break up the JSON. Don't forget to minify.
I think the desired architecture would be to use XHR or filesystem (if that's really your use case / local only) to grab what JSON you need on demand.
If you want to have the data directly, you have to put it in a .js file like you did. You could write a build rule to create this .js file from the .json file.
Another solution is using Ajax, which will allow from the js to fetch the content of the .json and store it into a variable.
You can use <link> element with rel attribute set to "import", get and pass link.import.body.textContent to JSON.parse() to create javascript object from JSON.
<script>
let json;
function handleJSON(link) {
json = JSON.parse(link.import.body.textContent);
}
window.onload = function() {
console.log(json)
}
</script>
<link id="json" rel="import" type="application/json" href="https://gist.githubusercontent.com/guest271314/ffac94353ab16f42160e/raw/aaee70a3e351f6c7bc00178eabb5970a02df87e9/states.json" onload="handleJSON(this)"/>
//basic method !! think about handling the exceptions...
if (window.XMLHttpRequest) { // Objet standard
xhr = new XMLHttpRequest(); // Firefox, Safari, ...
} else if (window.ActiveXObject) { // Internet Explorer
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// Ajax req
xhr.onreadystatechange = function () {
// if ok 200
if (this.readyState == 4 && this.status == 200) {
data = this.response
// your data
console.log(data[0].title);
}
}
xhr.open("GET", "resc/placeholder.json", true)
xhr.responseType = "json"
xhr.send(/*prams if needed */)
Related
I am trying to show multiple xml file into html. I able get single xml file show in html table by using xmlhttp.open("GET", "204S_2000_02_17_00_30_357.xml", true). However, I can't get multiple xml file using this function.
I had tried using xmlhttp.open("GET", "*.xml", true) but doesn't get any output.
It's any solution or method to "GET" the multiple xml file into html?
Noted: xml file will continuously generate in folder with random name.(example 204S_2000_02_XX_XX_XX_XX.xml).
code that show single xml file in html table
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "204S_2000_02_17_00_30_357.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
//coding....
}
One HTTP request gets one HTTP response.
In general, you can't get multiple files back from a single request using a wildcard.
You could, if you wrote suitable server-side code, have the server recognise a wildcard in the URL and respond by (for example) sending a zip file containing all the files that matched, or generating a new XML document containing the contents of all the files that matched.
Generally, however, you will make a separate request for each resource you want. Having determined all the URLs you wanted to request, you would probably want to use an API that supported promises (i.e. fetch instead of XMLHttpRequest) so you could feed them into Promise.all and run the next stage of the program once you had collected all the data.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "https://zbapi.herokuapp.com/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
This is my code. It is returning html text but i want it to load html output.
It is returning html text but i want it to load html output.
alert expects to be passed plain text.
You need to put the HTML source code somewhere which expects HTML source code.
For example, the innerHTML of an Element object.
The URL you are requesting, however, includes relative URLs and has its own JS. It doesn't make much sense to request it with JS and then try to render it. You would also certainly be better off just triggering navigation with location = "https://zbapi.herokuapp.com/".
You need to parsing HTML page to JSON with some parser on the server and send parsed data to the client in JSON format. For example, Himalaya (in Node.js).
Official repository of Himalaya
or use html2json (NPM Repository) to parse on client
So I know this is so lame to ask this question as I have spent a day searching on this subject without any success. As many others, I'm facing the crossdomain problem. The suggestion I see everywhere is to update the JSON file on a server or use localhost which I can't use because my assignment is not allowed to do so.
I am posting this question hoping there is some other solution for this.
I need to fetch data from a JSON file locally using pure JavasSript and Ajax which does not involve hosting on a server nor localhost (using absolute path is also a bad idea).
This is my code so far:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '/json/userinfo.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
(function() {
loadJSON(function(response){
var actual_JSON = JSON.parse(response);
console.log(actual_JSON);
})
})()
You won't be able to access local files using AJAX/XHR. Its not designed for this purpose.
What you can do is assign your json data into a variable in the json file,
var data = [{
}];
and then load your json file using script tag like below:
<script type="text/javascript" src="file_name.json"></script>
Now all the json data can be accessed using the data variable.
I have a php script to delete an old instance of a csv file and upload a new one and a javascript function to read the file. It was working fine until I added the php to delete the old file, and now for some reason the javascript function always fetches the same file even when it's changed.
I've gone in and checked the data.csv file and it's the new file but the function still fetches the old one. And if I delete the file manually the function still mysteriously accesses the data.csv file... even though it's deleted.
This is the php:
<?php
if(file_exists('upload/data.csv'))
{
unlink('upload/data.csv'); // deletes file
}
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, 'upload/data.csv');
?>
This is the javascript. Note: the variable "allText" will always be the contents of the old CSV file even if data.csv has changed or is deleted.
function LoadCSV(){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
I'm not sure why this is happening or how to fix it?
It's probably browser caching.
I like to use a random value in the url to trick the browser into thinking it is a different page:
Try this:
function LoadCSV() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv?nocache="+(Math.random()+'').replace('.',''), true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
The get parameter nochache doesn't mean anything to the server or browser, but fools it into fetching a new resource every time, at the cost of losing browser caching altogether. Technically it's possible(although spectacularly unlikely) to get the same value twice, so you can add time in milliseconds or something if you want to make it totally foolproof.
Note that this will also bypass almost all other types of caches as well.
I have this code that loads an xml file using javascript:
function getXmlDocument(sFile) {
var xmlHttp, oXML;
// try to use the native XML parser
try {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", sFile, false); // Use syncronous communication
xmlHttp.send(null);
oXML = xmlHttp.responseXML;
} catch (e) {
// can't use the native parser, use the ActiveX instead
xmlHttp = getXMLObject();
xmlHttp.async = false; // Use syncronous communication
xmlHttp.resolveExternals = false;
xmlHttp.load(sFile);
oXML = xmlHttp;
}
// return the XML document object
return oXML;
}
If the extension of the 'sFile' is not .xml the function returns "" always. What should I do to fix this?
I think it's a problem on the server side: files with another extension than .xml don't get the MIME type of text/xml or something alike and the browser('s XML parser) doesn't recognize it as XML.
Be sure that your content is served with the correct MIME type by your server software. With Apache, you can change this in the .htaccess file. Dynamically generated XML should be sent with an appropriate Content-Type: header. In PHP, you can do this with the header function.