I'm trying to download some data using pure javascript/html from cross-domain, dropbox to be specific.
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://dl.dropbox.com/u/6438697/padraicb.json?count=10&callback=myCallback"></script>
</body>
for some reason, the json is not loading. however the json loads correctly when I make the url "http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback" instead. I got this example from here
Can anybody explain why dropbox doesn't work?
thanks!
UPDATE:
<script type=text/javascript>
function myCallback(dataWeGotViaJsonp){
alert(dataWeGotViaJsonp);
}
</script>
<script type="text/javascript" src="http://dl.dropbox.com/u/6438697/test2?&callback=myCallback"></script>
returns either [object object] or undefined... something is still wrong? the contents of test.json is myCallback( {"your":"json"} );
You can't just add the word 'callback' to your URL and expect Dropbox to wrap it for JSONP. You put a JSON file on your Dropbox and shared it publicly, but Dropbox isn't a dynamic server. You need a scriptable environment to take the callback parameter value and wrap it around the JSON in order to make it "JSONP".
The reason the Twitter URL works is that their API is configured to take the callback parameter as a sign that the client is expecting JSONP, which is really just a fancy term for "a JavaScript object literal wrapped in a callback function". You tell twitter what that function will be called, and they'll return a file that the browser will execute as a script, passing the object as a parameter to your callback function.
If you don't need the JSONP callback function name to be dynamic AND you need to use Dropbox, just wrap the JSON yourself. All you need to do is edit the file, and prepend valid JSON with the name of the function, and append it with the close paren.
ie,
myCallback( {"your":"json"} );
It is possible to use Google Apps Script as a proxy for hosting sites that do not support jsonp. There is writeup on how to do it here http://ramblings.mcpher.com/Home/excelquirks/jsonp
Related
I am trying to pull out the data with src=""; and load it into variable but with no success.
Here is the code i have been working with:
var JSONObject = document.getElementById("data").innerHTML;
console.log(JSONObject);
<script type='text/javascript' src='https://www.instagram.com/xsolvesoftware/media/' id="data"></script>
innerHTML means exactly what it says: the inner HTML. It is the HTML between <script> and </script> of which there isn't any.
If you want to read the JS then you need to getAttribute('src') and then make an HTTP request for it (e.g. with fetch or XMLHttpRequest).
The Same Origin Policy will probably block this.
Enviroment: Visual Studio 2012, MVC4, Razor, Internet Application.
I'm working with eBay API and I want to show the search results (JSON).
I have a view page with code...
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
This line in ".js" file:
var url = "http://ebay.com?..."
How can I execute this url from ".js" file automatically, when I openning this View Page? (This url sending request to Ebay server and receiving data, which will be showed on this View Page.)
I will change a question a little...
If I'm running this code from the View page, everything works fine:
<script src=http://ebay.com?... </script>
How can I receive this part("http://ebay.com?..." as a variable) from ".js" file? Is it possible?
If you just want to send the request, you could add an image to the DOM with that as the src, for instance.
If you want to receive data from the request, you're going to have to do an AJAX call. This is handled quite differently in different browsers, so here's a good idea to use a framework, such as jQuery.
Since the URL is on a different domain than yours, however, you won't be able to access it with a regular AJAX request. You'd have to refer to what is called a JSONP request. This requires that the document you're fetched is formatted in a specific manner to allow this. If it isn't, JavaScript simply won't allow this interaction, due to the Same-Origin Policy.
JSONP requires that the remote document has the following format:
someCallbackFunction(javaScriptObjectWithData);
If it does, you'd be able to include a script file to the DOM with that URL as the src, the content of the document, once fetched, will be immediately executed in your browser. You should by then have specified a callback function with a name matching the callback being made in the document (this is usually something you can specify with through querystrings in the original request).
If none of these options are available for you, because of the format of the remote document, then you're going to have to request the document from server side. If you don't have access to a serverside environment yourself, in order to do this, there is the option of using somebody elses server. Yahoo's custom query language – YQL – can be used for querying the content of remote documents, and YQL is available through JSONP, so you could possibly relay your request through them.
See this post on using YQL with JSONP
Update, now that you've added more data, eBay API is available for JSONP, and I think that's the solution you're looking for.
Resolved...
<script src="/Scripts/ebay.js" type="text/javascript"></script>
<script>
s = document.createElement( 'script' );
s.src = url;
document.body.appendChild( s );
</script>
I've done some research on the subject, but can't get a clear answer with how to go about doing this. I have tried the following method:
<script type="text/javascript" src="../binaryajax/binaryajax.js" ></script>
<script type="text/javascript" src="id3.js" ></script>
var file = "mymusicfile.mp3";
// define your own callback function
function mycallback() {
// either call ID3.getAllTags([file]) function to return object holding all the tags
alert(
"All tags in this file: " + ID3.getAllTags(file).toSource()
);
// or call ID3.getTag([file], [tag]) to get a specific tag
alert(
"Title: " + ID3.getTag(file, "title") + " by artist: " + ID3.getTag(file, "artist")
);
}
ID3.loadTags(file, mycallback);
The first method, (getAllTags) doesn't allow my script to run, and the second method returns null for both title and artist on all of my mp3's.
Source of Info: http://blog.nihilogic.dk/2008/08/reading-id3-tags-with-javascript.html
I know these methods are using ID3(v1), so that may be the problem. Either that, or I suppose it's possible by mp3's don't contain ID3 information. But if anyone could provide some insight into how to do this, or how to identify if my mp3's contain ID3 info and whether it's v1 or v2 would be great.
Edit: I should say, I'm accessing the files via Blob URL's because the app that I'm developing let's the user select a directory on their computer and then queries the files for media files. In doing this, you can't access the absolute path of the file, but you still can access the file information and use the file.
For others to use: this worked quite well for me :)
github.com/aadsm/JavaScript-ID3-Reader/tree/master/src use the project repository
Hi I'm trying to get contents of the link tag. So with:
<link rel="stylesheet" href="some.css">
I want the contents of the file some.css in a string.
Tried:
document.getElementsByTagName('link')[0].firstChild.nodeValue; // fails
document.getElementsByTagName('link')[0].hasChildNodes(); // false
Any ideas? I don't want to use the styleSheet method (which only works in FF anyway) because it will strip out stuff like -moz-border-radius and such.
Thanks.
I think Daniel A. White is correct. Your best bet is to get the href of the stylesheet, then load the content via Ajax and parse it.
What are you trying to do exactly?
You can't get the contents of a file with only javascript. You'll need an ajax request to the server which opens the file and returns its contents.
To do this, you need to access the file via an ajax request.
So, with jQuery, something like this
$.ajax({
url: "some.css",
success: function(){
//do something
}
});
More details here: http://api.jquery.com/jQuery.ajax/
Note: this only works if the file making the request is on the same server as the file requested.
CSS rules offer a special API, but nothing like innerHTML.
This is as close as it gets:
var result = '';
var st = document.styleSheets[0].cssRules;
for (var i = 0; i < st.length; i++) {
result += st[i].cssText;
}
console.log(result);
However, this will not respect whitespace, comments, erroneous rules, ...
And as usual, this is subject to Same Origin Policy.
Lets say I have a page with this code on it on www.foo.com:
<script src="http://www.bar.com/script.js" />
Can I write code from within script.js that can check that it was served from bar.com? Obviously document.location.href would give me foo.com.
Thanks!
var scripts = document.getElementsByTagName("script");
give you a collection of all the scripts in the page
After this you can read their src property to find your target (I hope you know how the script is called)
for (var i=0, limit=scripts.lenght; i< limit; i++) {
if (scripts[i].src.substr(<calculate your offset>) == scriptName) {
// Have you found your script, extract your data
}
}
The only way to find out the location of a non-worker script is the non-standard error.fileName, which is only supported by Firefox and Opera:
var loc = (new Error).fileName;
If the script is a worker thread (which of course it isn't), then you could just use the location object.
If it's really important, you could work around it by defining a string containing the script URL in front of each script tag:
<script type="text/javascript">SCRIPT_URL = "http://www.bar.com/script.js"</script>
<script src="http://www.bar.com/script.js" />
Inside the script file you can then access the URL
alert("my URL is "+SCRIPT_URL);
Not too elegant but should work.
You could also, if you have a server-side language like PHP and don't mind sending JS files through the interpreter (Big performance caveat!), do something like this within the JS file:
<script type="text/javascript">var my_url = "<? echo $_SERVER["REQUEST_URI"]; ?>"</script>
but that should really, really be the last resort.
You can wrap your script in a condition, kind of like an adult diaper, if you insist.
if(top.location.host==='www.bar.com'){
//the whole script goes here
}
else alert('Nyah Nyah Nyah!')