Reputation: 241
Is there a way to link external JSON Data within JSFiddle?
The portion of code that I am attempting to have pull in the JSON Data with is as follows:
var xhr = new XMLHttpRequest();
xhr.open('GET', url: 'www.myurl.com/js/data/data.json', true);
xhr.send(null);
I have seen JSON Data placed within the javascript section/internally placed within the JSFiddle, but I was curious if it was possible to pull in the JSON Data externally using it's url path in JSFiddle.
View the current JSFiddle.
Upvotes: 1
Views: 1282
Reputation: 6770
You can simulate a JSON call by using the /echo/json/ URL. In your exemple you must the content of your JSON file
{
"profiles": [
{ "firstName": "Jane", "lastName": "Doe", "gender": "female" },
{ "firstName": "John", "lastName": "Doe", "gender": "male" },
{ "firstName": "Akexander", "lastName": "Beth", "gender": "male" },
{ "firstName": "Sarah", "lastName": "Kelly", "gender": "female" }
{ "firstName": "Rachel", "lastName": "Haiworth", "gender": "female" }
]
}
and use it as a parameter to a POST /echo/json/ request.
var JSONData = {
"profiles": [
{ "firstName": "Jane", "lastName": "Doe", "gender": "female" },
{ "firstName": "John", "lastName": "Doe", "gender": "male" },
{ "firstName": "Akexander", "lastName": "Beth", "gender": "male" },
{ "firstName": "Sarah", "lastName": "Kelly", "gender": "female" }
{ "firstName": "Rachel", "lastName": "Haiworth", "gender": "female" }
]
}
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode(JSONData),
delay: 3
},
onSuccess: function(response) {
// Function to onSucess
}
}).send();
See http://doc.jsfiddle.net/use/echo.html
Upvotes: 1
Reputation: 18881
Your example (including the code in the fiddle) is broken.
You fix it by using this isntead:
xhr.open('GET', 'http://www.andrewwierzba.com/js/data/data.json', true);
Then, however, you hit a brick wall:
XMLHttpRequest cannot load http://www.andrewwierzba.com/js/data/data.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
How to fix that is for another question and there's a lot of talk about cross-origin XHRs on the net, so try to look it up. It's pain, that's why most people embed the json instead.
A better idea may be to use the "echo" feature, as mentioned by @cirtrus in the comment on the original post.
Upvotes: 1