I want to dynamically make different YouTube JSON API requests and then use a function to sort the data I want.
Currently following the examples on the YouTube data JSON API site here.
Here is my current code which is getting me the id's nicely.
My question is currently it's using a script tag and the callback URL query to use my function. Is there a different way that I can implement in JavaScript only and keep doing requests that call my getid function?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
function getid(data) {
var i=0;
for(items in data.data){
i++
console.log(data.data.items[i].id)
}
}
</script><script type="text/javascript" src="https://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc&callback=getid"></script>
</body>
</html>
jsonp function below will dynamically create a script tag and append it to the body.
function jsonp(url,callback) {
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
}
function getid(data) {
var i=0;
for(items in data.data){
i++
console.log(data.data.items[i].id)
}
}
// pass a url and callback
var url = "https://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc&callback=getid";
jsonp(url, getid)
Related
I am trying to parse this HummingBird api with sample url :
http://hummingbird.me/api/v1/search/anime?query=naruto
However, I do not know how to get each id seperately , or each name seperately. For e.g:-
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = //make this display name
</script>
</body>
</html>
I want the demo element to display the title of the first one in the list. Can anyone tell me how I can possibly do this?
If you use jQuery below is the snippet you can use.
var results = "";
$.get("http://hummingbird.me/api/v1/search/anime?query=naruto",function(data){
results = JSON.parse(data);
});
console.log(results);
Download JQuery from here and put the file next to your html.
Add this element between the html tag and the body
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
Replace document.getElementById("demo").innerHTML = with:
$(document).ready(function(){
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null, function (data) {document.getElementById("demo").innerHTML = data[0].title})
})
JQuery is a JS library that makes life easy.
The function below takes 1 function as an argument and executes it after the page has loaded
$(document).ready()
The next function makes an HTTP GET request and parses the response to js object
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null,...)
The next function gets the title of the first element of data
function (data) {document.getElementById("demo").innerHTML = data[0].title}
mmm try this fiddle i don't know exactly how you read the file but if you get a string do the JSON.parse(STRING) before.
https://jsfiddle.net/79a1abbL/3/
After executing document.write(), Google Chrome shows me that the HTML codes is changed from Code A to Code B. It seems that document.write() overwrite the entire page. If yes, how to append the script tag inside head tag?
Code A : Before Executing document.write()
<!--DOCTYE html-->
<html>
<head>
<script src=".\js\main_CasCode.js"></script>
</head>
<body onload="main()">
<p>hi</p>
</body>
</html>
Code B : After Executing document.write()
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
</html>
JavaScript in File .\js\main_CasCode.js
function main() {
//console.log = function() {};
loadjQuery();
//waitjQueryLoaded_and_start();
}
function loadjQuery() {
console.log("Loading jQuery...");
var s = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>';
document.write(s); //<----Problem Here
}
That's because document.write erases and rewrites the document when the document has already finished rendering (like after onload). It only appears to append when called during the rendering of the page.
A better way to do this is to dynamically create a script element, add it to the page, and add an src which triggers the loading mechanism.
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
In other news, why are you loading jQuery dynamically when you have control of the page? Why not add it directly as a <script> on the HTML?
I don't think you want to be using document.write at all. You can use the following. Make a script element, and append it to the head element
var head = document.getElementsByTagName('head')[0]
var s = document.createElement('script')
s.src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"
head.appendChild(s)
document.write overwrites the whole DOM
You can create a function
function loadjQuery() {
console.log("Loading jQuery...");
var scrpt = document.createElement('script');
scrpt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
document.head.appendChild(scrpt);
}
We give out a piece of javascript tags such as <script src="http://ours.com/some.js"></script> which site owners put on their site like http://example.com and in this javascript tag we want to dynamically include a third-party js such as which can have document.write in it, but of course if we try to include it by conventional method,
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.src="http://third-party.com/some.js";
document.getElementById('target').appendChild(script_tag);
we get a warning from browser,
Warning: A call to document.write() from an asynchronously-loaded
external script was ignored.
How do we get around this? Keep in mind, we don't really have control over third-party scripts so we can't change the logic in it. We are looking for some solution which can work across all browsers.
The problem with loading a script on a already loaded document (instead of having the browser ignore the document.write()) is that you would delete all existent HTML. See this example so you can understand exactly what's happening, or for more details look at a documentation page for the document.write() method.
While I know this might not be what you're expecting to get as an answer, I believe you are out of luck since rewriting the script is not an option.
This appears to be a similar question with similar replies.
You can support script injection the correct way by intercepting calls to document.write in this way:
document.writeText = document.write;
document.write = function(parameter) {
if (!parameter) return;
var scriptPattern = /<script.*?src=['|"](.*?)['|"]/;
if (scriptPattern.test(parameter)) {
var srcAttribute = scriptPattern.exec(parameter)[1];
var script = document.createElement('script');
script.src = srcAttribute;
document.head.appendChild(script);
}
else {
document.writeText(parameter);
}
};
Obviously this can be condensed down a bit further, but the variable names are included for clarity.
Source
How about instead of loading the script by appending a script element, you load the contents of the script URL with an AJAX call and then use eval() to run it in the global scope? Here's an example and I did test it to verify that it works:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.eval(xmlhttp.responseText); //Indirect call to eval to execute in global scope (http://perfectionkills.com/global-eval-what-are-the-options/)
}
}
xmlhttp.open("GET", "https://third-party.com/test.js", false); //This is synchronous so that any document.write calls don't overwrite the entire page when they get called after the document is finished rendering. For all intents and purposes, this just loads the script like any other script, synchronously.
xmlhttp.send();
</script>
</head>
<body>
<div><h2>Hello World</h2></div>
</body>
</html>
And here are the contents I had in the test.js file:
document.write("This is a test...");
alert("...This is a test alert...");
console.log("...And a console message.");
I made the AJAX request for the script synchronous so that it would be loaded exactly as if it were a regular embedded script tag. If you run it asynchronously, and the script uses document.write after the page has been fully rendered, it clears the DOM and then writes to it... Kind of annoying actually. Lemme know if this works for you. :)
Document.write will not work from async script because document is already loaded when script starts working.
But you can do this:
document.body.innerHTML = document.body.innerHTML + '<h1>Some HTML</h1>';
Another procedure is to change the behavior of document.write() function.
Assume you have the main index.php file:
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
Hello<br>
<div id="target"></div>
<script>
document.write = function(input) {
document.body.innerHTML += input;
}
var doit = function() {
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.src="http://127.0.0.1:8080/testPlace/jsfile.js";
document.getElementById('target').appendChild(script_tag);
}
</script>
</body>
</html>
and the jsfile.js is like this:
document.write("OK MAN!");
now if you type doit() in the js browser console to execute that function (and the script do what you wrote) then the result would be:
Hello
OK MAN!
In which the html is like this:
<html><head>
<meta charset="utf-8">
</head>
<body>
Hello<br>
<div id="target"><script src="http://127.0.0.1:8080/testPlace/jsfile.js" type="text/javascript"></script></div>
<script>
//That Script which here I removed it to take less space in answer
</script>
OK MAN!</body>
</html>
What is the 3rd party javascript file?
If it's Google Maps JavaScript API v3 then make sure you include "&callback=your_init_funct" in the script URL. Then it will call 'your_init_funct' once the maps library is loaded so that you can begin displaying the map.
Another solution would be bezen.domwrite.js which is available here: http://bezen.org/javascript/index.html
Demo: http://bezen.org/javascript/test/test-domwrite.html
Yes, document.write can't be called from an asynchronously loaded script, because it's detached from the document, so it can't write to it.
You can see the approach used here for the google maps api to get around this problem. So, it is possible some of your 3rd party scripts that you haven't named, could have the similar callback pattern implemented.
https://developers.google.com/maps/documentation/javascript/examples/map-simple?hl=EN
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
</body>
</html>
I'm newbie in javascript and My project can't use AJAX or any Framework . . .
It's simple code but still curious what's wrong with it
<html>
<head>
<script type="text/javascript" src="onejs.js"></script>
<link href="onecss.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="myDiv" class="subMenu" onclick="test(this)">CLICK</div>
</body>
</html>
onejs.js
function test(id) {
var s = document.createElement('script');
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://echo.jsontest.com/one/111oneoneone/key/value";
var obj = JSON.parse(s);
id.innerHTML = (obj.key);
}
When I click in "CLICK" it doesn't change.
You are trying to load JSON as if it was a JavaScript script. It isn't, so you can't.
Normally you would use the XMLHttpRequest object for this type of job.
However, since you are ruled out Ajax (the process of using JavaScript to make HTTP requests), this isn't an option, so you would have to embed the data into the HTML when it initially loads.
I have a small web page with a single div whose content needs to be updated periodically. The server sends JavaScript with a function that contains the new data to be updated in the div. Here's the first part of the code that the server sends:
<html>
<head>
<script>
function bar() {
document.getElementById("foo").innerHTML = "0";
}
</script>
</head>
<body onLoad="bar()">
<div id="foo"></div>
</body>
After a delay (2 seconds), the server sends in the remaining code below:
<script type="text/javascript">
function bar() {
document.getElementById("foo").innerHTML = "1";
}
</script>
</script>
</html>
The trouble is that I never see the div show "0" in it - the browser waits until the entire page is loaded, and straightaway displays "1" in the div. How do I get the div to show "0" in it while the server has not sent the entire page?
I am not looking at using any jQuery or AJAX code - please limit your answers to JavaScript only.
You can not use onload -> that gets fired only after the whole page has completely loaded.
Also you have to add some more bytes to the first response, because most browsers only start incremental rendering of the page after a certain ammount of data being received.
This should work:
<html>
<head>
<script>
function bar(x) {
document.getElementById("foo").innerHTML = x;
}
</script>
</head>
<body>
<!-- AAAAAAAAAAAA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script type="text/javascript">
bar(0);
</script>
</body>
--- DELAY ---
<script type="text/javascript">
bar(1);
</script>
</script>
</html>
Here is a working example in node.js:
var http=require('http');
var server=http.createServer(function(req,res){
res.write('<html><head> <script> function bar(x) { document.getElementById("foo").innerHTML = x; }</script> </head> <body><!-- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA --> <div id="foo"></div><script>bar(0);</script> </body>');
setTimeout(function(){
res.end('<script type="text/javascript"> bar(1); </script></html>');
},2000);
});
server.listen(8080);
it first shows "0" then after 2 seconds "1"
I'm not sure it's possible to do it the way you're trying. The browser will always wait till the page has fully loaded, so it will always wait till you send that second batch.
If you don't want to use AJAX or jQuery, you could try a hacky version to get what you want.
What you can do is specify a callback function on your page to populate the div with a parameter, so something like
callback = function(data) {
document.getElementById('foo').innerHTML = data;
}
Then, you set a timeout on your page to send a request to your server to dynamically load a javascript file that calls that function. So again:
myTimeout = function() {
var script = document.createElement('script');
script.src = "http://myserver.com/mydynamicscript";
document.getElementByTagName('head').appendChild(script);
}
setTimeout(myTimeout, 2000);
The script that you're loading can either be static, or some servlet/php file that returns a javascript file, i.e. it sets it's content-type header to "text/javascript".
In that script, you would then generate this:
callback("whatever I want to put in my div...");
Once that has been loaded, it will call the previous function you declared earlier, and load the content in that div.
It's effectively a hacky form of AJAX, but not AJAX.