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.
Related
I am using a node sever to send a table from a sqlite db to the browser. This table contains filename and path of a pdf file that I want to render on the browser. Until now I was using hard coded paths for the the pdf file and rendering. But now i have setup a get route and a controller in node such that whenever '/content' is hit in browser , the server queries the database and and sends the data to the client. To the send the data I am using
res.render('content/index',{data:queryData});
Now, how do I access this data using client side javascript so that I can pass the path of the pdf file to the function that renders the pdf? I have done research and the nearest answer I got was using XMLHttpRequest. I tried this method
var xhr = new XMLHttpRequest();
const path = "http://localhost:3000/content";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
{
var myResponseText = xhr.responseText;
console.log(myResponseText);
}
};
xhr.open('get', path, true);
xhr.send();
When I do this I get the entire html code for the view. Not the data I expected. How do I solve this issue. I have done some more reading while writing this post and I suppose. I have set a header somewhere? But the documentation says
app.render(view, [locals], callback)
which means res.render can take local variables, shouldn't be setting the headers?
You should return json instead of render template:
app.get('content/index', (req, res) => {
res.json({data: queryData});
});
I am using pdf.js
PDF.js needs the PDF file, e.g.:
pdfjsLib.getDocument('helloworld.pdf')
I'm assuming your queryData goes something like this:
{ filename: 'file.pdf', path: './path/to/file.pdf' }
I'm not sure what's in your content/index or what path this is on, but you obviously need to find a way to make your PDF file ('./path/to/file.pdf') available (as a download). See Express's built-in static server or res.download() to do that.
Once you have the PDF file available as a download, plug that path into PDF.js's .getDocument('/content/file.pdf') and do the rest to render the PDF onto the canvas or whatever.
Hope that helps.
Is it posible to request a JSON object from my browsers local storage with Ajax? it's just a simple object that i made with Js, and converted into JSON.
I then stored it to local browser storage, but i'm not sure that will work, considering that it might only work to request from a server.
I have seen simular questions about this, but i only see examples of jQuery, not pure JavaScript and AJAX.
<p id="demo"></p>
<script>
var info = {
name: "Josh",
age: 22,
born: "New York"
};
var jason = JSON.stringify(info);
localStorage.setItem("myJason", jason)
var http = new XMLHttpRequest();
http.open("GET", "file:///D:/HTML%20Files/Nettside%20med%20JSON%20og%20AJAX/nettside.html", true);
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
http.send();
If you are running the html file from the local disk then yes you can access it by navigating the file structure using "../" to go up a file, however if the HTML file has been loaded from a web server then the only way to access it is to use a file input and then read the file contents. The user must choose the file though.
Here is an article on reading binary data from a file that the user has selected.
https://www.html5rocks.com/en/tutorials/file/dndfiles/
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 */)
I am creating a weather based artwork-change to be hosted on a local machine with the JSON file updating through an FTP sync. This means that the JSON file will be sourced locally on the same computer. Below is my current code for sourcing the JSON externally. Could you help me with sourcing this locally. Would I just change the URL to the file pathway of where it will be sitting? and remove the GET and send parts.
var xhr = new XMLHttpRequest();
var URL = "http://api.openweathermap.org/data/2.5/weather?q= {London}&appid=genericAPIpassword";
xhr.open("GET", URL, false);
xhr.send();
var weatherResponseStringify = JSON.stringify(xhr.responseText, "", 2);
var weatherResponseParse = JSON.parse(xhr.responseText);
Thank you all for helping!
var myInternalSource = {
key:value,
key:value
}
No need to overcomplicate things. If the json is in another file, then do:
<script src="externalFile.js" ></script>
Or use System.JS Import if you need asychronisity.
I am building a javascript component for Firefox that will take in a zip code, and will return the current weather conditions.
The sample code that weather underground uses jQuery, but as I understand it, I cannot include this code in my javascript component, as javascript does not have the functionality to include other javascript files.
At any rate, I have built up my skeleton code. It takes in the zip code and builds up the url
(example: http://api.wunderground.com/api/e17115d7e24a448e/geolookup/conditions/q/22203.json)
I have tried downloading the data from that url, via the following method:
getWeatherByUrl: function(url)
{
var persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",Components.interfaces.nsILocalFile);
file.append("weather-forecaster.dat");
var urlURI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);
persist.saveURI(urlURI,null,null,null,"",file);
return url;
}
This should download the file to the user's profile directory. It indeed does create the file there. However, it does not look like it contains the json data from weather underground.
What exactly is going on? How would I download the file? I believe that there is a query going on when that url is passed to weather underground, but that shouldn't matter as the .json page is what gets spit out from them, right?
Is there a way to do this without downloading the file, but by streaming it and parsing it?
You can simply use XMLHttpRequest to download this data:
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json");
request.addEventListener("load", function(event)
{
var data = JSON.parse(request.responseText);
alert(data.response.version);
}, false);
request.send(null);