i have a url which returns a json file(i have typed the url in the address bar and it showed the json output) but i don't know how to request for the json file in javascript. can anybody help me?
here's the code:
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=kalutara&format=json&num_of_days=4&key=myKey' ;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.open('GET', url, true);
http_request.send(null);
http_request.onreadystatechange = function() {
if ( http_request.readyState == 4) {
if ( http_request.status == 200)
success( http_request.responseText);alert(http_request.responseText);
else if (failure)
failure( http_request.status, http_request.statusText);
}
};
Thanks !!
It depends on how you json file looks like.
For e.g.
If the file contains something like
var obj =
{
//Object definition...
}
Then you can just use the regular script tag to be able to use the json object.
If the file in format:
{
//Object Definiton
}
then you can read the contents as defined in your post (Using XMLHTTP request) however then use eval function to make it available in the page something like the one below in your success() method:
eval("var obj = " + http_request.responseText);
Related
I would like to have a WordPress text widget with a javascript that would populate the widget with text from some .txt file (this is to allow dynamic content on a cached page by allowing me to update that text file with new HTML content).
I found this thread and tried the following code, which did not work:
<script type="text/javascript">
function read(textFile){
var xhr=new XMLHttpRequest;
xhr.open('GET',textFile);
xhr.onload=show;
xhr.send()
}
function show(){
var pre=document.createElement('pre');
pre.textContent=this.response;
document.body.appendChild(pre)
}
read('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
</script>
Any suggestions on how to fix it?
Do you know Javascript or are you just hoping for a copy and paste solution? Perhaps try reworking this code here:
function getStuff(url) {
var xhttp, jsonData, parsedData;
// check that we have access to XMLHttpRequest
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// get the data returned from the request...
jsonData = this.responseText;
// ...and parse it
parsedData = JSON.parse(jsonData);
// return the data here
// if the data you're returning is an object
// you need to know the endpoints
// for example, if there was a username,
// you might return parsedData.username
var something = parsedData.endpoint;
// debug / test
console.log(something);
var elementToShowStuffIn = document.getElementById('theIDOfTheElement');
elementToShowStuffIn.innerHTML = something;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
getStuff('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
Yes, this works. Just replace this line here: var something = parsedData.foo.bar;
I'm new to javascript which should be really simple to solve, but I am lost as of now.
I have a url: http:getall.json
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:
request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
your result will be in the data variable.
JSONP calls:
function getJSONP(url, callback) {
var script = document.createElement('script');
var callbackName = "jsonpcallback_" + new Date().getTime();
window[callbackName] = function (json) {
callback(json);
};
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
//jsonObject is what you want
});
Regular ajax ajax call:
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
function getJSON(url, callback) {
req = getXHR();
req.open("GET", url);
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObject = null,
status;
try {
jsonObject = JSON.parse(req.responseText);
status = "success";
} catch (e) {
status = "Invalid JSON string[" + e + "]";
}
callback(jsonObject, status, this);
}
};
req.onerror = function () {
callback(null, "error", null);
};
req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
//jsonObject is what you want
});
I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource
with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:
A PHP Error was encountered
...
In your HTML include your json file and a js code as modules
<script src="/locales/tshared.js" type="module" ></script>
<script src="/scripts/shared.js" type="module" ></script>
file content of tshared
export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;
Adapt path and names as needed, use locale at will.
I'm starting up playing with Win8 development and I'm stucked in a problem since yesterday.
I've followed the MSDN example HERE to grab the data, I can retrieve the data (therefore, isn't a connection limitation issue) but the problem is that regardless the settings I use, it always retrieve data as plain text, including \r\n characters.
I assume that if I could retrieve the structured XML would make my job easier, so I'm hoping you folks can put some lights on what I'm doing wrong.
Here's my code snippet:
<div id="xhrReport"></div>
<script>
var xhrDiv = document.getElementById("xhrReport");
xhrDiv.style.color = "#000000";
WinJS.xhr({ url: "http://www.w3schools.com/xml/note.xml", responseType: "responseXML"})
.done(
function complete(result) {
var xmlResponse = result.response;
xhrDiv.innerText = "Downloaded the page";
xhrDiv.style.backgroundColor = "#00FF00"; //here goes my breakpoint to check response value
},
function error(result) {
xhrDiv.innerHTML = "Got error: " + result.statusText;
xhrDiv.style.backgroundColor = "#FF0000";
},
function progress(result) {
xhrDiv.innerText = "Ready state is " + result.readyState;
xhrDiv.style.backgroundColor = "#0000FF";
}
);
</script>
Here's the value of xmlResponse
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<!-- Edited by XMLSpy® -->\r\n<note>\r\n\t<to>Tove</to>\r\n\t<from>Jani</from>\r\n\t<heading>Reminder</heading>\r\n\t<body>Don't forget me this weekend!</body>\r\n</note>\r\n"
And HERE is a similar question, which seems to be working using the responseXML responseType (although it's not documented #MSDN guide).
Some things I already tried:
Use a responseType as 'document' (as per the MSDN guide) and then retrieve result.responseXML;
Omit the responseType argument;
Use the approach above.
Now, I ran out of ideas. Any thoughts?
Try To use the following code to get the tags you want to play... (I believe it will do exactly what you want/need, connecting to a webpage and than work on the result based o the webpage/xml tags
function connectToURL(){
var url = "";
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
return;
}
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
}
// your job will actually start on this one...
function stateChanged() {
if(xmlHttp != null )
if (xmlHttp[item.key].readyState == 4 ) {
try {
var xmlDoc = xmlHttp.responseXML.documentElement.getElementsByTagName("TAGYOUWANTTOGET");
for (var i = 0; i < xmlDoc.length; i++) {
xmlDoc[i].getElementsByTagName("TAG")[0].childNodes[0].nodeValue
}
} catch (e) {
//work on the exception
}
}
}
}
function GetXmlHttpObject(){
var xmlHttp=null;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
I think you should set an option for responseType : "document" just like:
WinJS.xhr({
url: "http://www.capital.bg/rss/?rubrid=" + groupId,
responseType:"document"
}).then(function (result) {
console.dir(result.response);
});
I have a web application that receives json from a server. I was using this code:
var http_request = new XMLHttpRequest();
var url = "url where I have the json"
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
var obj;
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
obj = eval("(" + json_data + ")");
processData(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
But now I want to receive json from two url's and show the information. How can I do this using JavaScript? I know eval is not the appropiate thing to do but this is just a prototype.
Thank you so much! :)
As others have mentioned, you simply need to make 2 requests. In order to re-use the code you have already written, you could define a function to get json that takes a url argument. Something like this:
function getJson(url, callback){
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
var parser = (JSON && typeof JSON.parse == 'function') ? JSON.parse : eval;
var obj = parser("(" + json_data + ")");
callback(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
}
I replaced the call to eval with some logic that will call JSON.parse if it is present, otherwise it will use eval. Using this function would allow you to make multiple requests by calling it multiple times, like so:
getJson("some url", processData);
getJson("some other url", processData");
If you wanted to process data from different urls in different ways, just define another function similar to processData and pass it along instead, like getJson("some crazy url", processCrazyData);
Using a framework like jQuery would reduce the amount of code that you have to write, but this solution should get it done using basic javascript.
The easiest way would be to put it into a function.
function getJson(url) {
//Remove the var url="string" line
//Rest of code
}
function handleJson() {
//Other code
}
Alternatively, you could use jQuery, in which case your code would be:
$.getJSON('url goes in here',function(data){
processData(data);
});
And just use that whenever you want to grab a page.
I would like to retrieve fullpath of a file and pass it to javascript. The requirement is that I need to retrieve XML file using JavaScript.
If it is a file you can access relatively to your web page do something like:
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
Assuming you have your web page next to the abc.xml...
This doesn't specify how to get full path to the XML - do youi still need it or loading it is enough?
For cross browser (from: http://developer.apple.com/internet/webcontent/xmlhttpreq.html)
var req;
loadXMLDoc("abc.xml");
function loadXMLDoc(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send("");
}
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
alert(req.responseXML);
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}
}
}
If you know the exact file up front, you can create a server-side program (i.e. service) to read the file, parse it and output it.
Then you'll just need to write some Javascript to make an AJAX call to this service (check out a Javascript library like Prototype or JQuery) to read the output of the service and thus the contents of the file.