In my application, I make an ajax call that renders this template with js:
<div id="ajax_reply">
<div id="hidden_data" style="display:none;"></div>
<script type="text/javascript">
var data = [];
data.push(['Col1', 'Col2', 'Col3', 'Col4']);
{% for entry in mydata %}
var dCell = [];
dCell.push({{ entry.Col1 }});
dCell.push({{ entry.Col2 }});
dCell.push({{ entry.Col3 }});
dCell.push({{ entry.Col4 }});
data.push(dCell);
{% endfor %}
document.getElementById('hidden_data').innerHTML = JSON.stringify(data);
</script>
</div>
This doesn't work, if I run the resulting js manually in console, it does get inserted into the div, but otherwise, the javascript is never executed. I've searched on SO but couldn't find questions on this exact topic. hidden_data is in scope, any suggestions?
EDIT:
Code seen in console after wrapping in onload (I had to make a few edits but running this manually in console works)
<div id="ajax_reply">
<div id="hidden_data" style="display:none;"></div>
<script type="text/javascript">
window.onload = function() {
var data = [];
data.push(['Col1', 'Col2', 'Col3', 'Col4']);
var dCell = [];
dCell.push('1233');
dCell.push('123312');
dCell.push('1233');
dCell.push('1482.61');
data.push(relation);
var dCell = [];
dCell.push('1231');
dCell.push('2112.0');
dCell.push('1231');
dCell.push('123123.00');
data.push(relation);
document.getElementById('hidden_data').innerHTML = JSON.stringify(relationsData);
};
</script>
</div>
If entry.Col1 contains string 'my text', resulting template will give you lines like this:
dCell.push(my text);
and, i suppose, you need
dCell.push('my text');
Make sure that this is executing after the DOM is loaded.
Try wrapping your script like:
window.onload=function(){
//script here
}
You can see on jsfiddle that this should be working.
Update:
It seems to be a problem with how Django is inserting data since it works with hardcoded sample data. Try the escapejs template filter to handle any potential javascript escaping problems. I've had to debug similar problems before with newlines and '&' symbols in particular.
dCell.push("{{ entry.Col1|escapejs }}");
Related
I'd like to pull data from my HTML code into my dataLayer (Google Tag Manager).
The html code is something like this:
<body class="portal sessions" data-place="hun">...</body>
And the Javascript Code is something like this:
<script type="text/javascript">
var lang_log = document.getElementsByClassName("portal");
dataLayer.push({
"language_login":lang_log
})
</script>
What I'd try is to give to the lang_log variable the "hun" value and I'd try:
<script type="text/javascript">
var lang_log = document.getElementsByClassName("portal")['data-place'];
dataLayer.push({
"language_login":lang_log
})
</script>
But it's not working.
Any ideas?
Any help or advice is apprecaited, Thank you in advance.
document.getElementsByClassName("portal") returns an array-like collection of elements.
You can get the first element of this collection with document.getElementsByClassName("portal")[0].
To access the data attribute, use document.getElementsByClassName("portal")[0].dataset.place.
var AdataLayer = [];
var lang_log = document.getElementsByClassName("portal")[0].dataset.place;
AdataLayer.push({
"language_login":lang_log
})
console.log(AdataLayer);
console.log(AdataLayer[0].language_login);
<body class="portal sessions" id="portal" data-place="hun">...</body>
Found the solution:
the JS should be:
<script type="text/javascript">
var lang_log = document.getElementsByTagName("body")[0].getAttribute("data-locale");
dataLayer.push({
"language_login":lang_log
})
</script>
Still investigating in why the first version did not work!
I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.
I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}
Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
http://jsfiddle.net/UBw44/
You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);
Try this:
console.log(($("script")[0]).innerHTML);
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}
The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.
Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "<")
.replace(/>/g, ">")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN
I'm working with mustache.js for the first time. All the examples I'm finding seem to talk about putting everything inline, but I want my templates in external files so they can be used in multiple places. How do I do that? (I've got jQuery in my stack, if that makes a difference.)
So say I have:
template.html
{{title}} spends {{calc}}
data.js
var data = { title: "Joe", calc: function() { return 2 + 4; } };
index.html
<script type="text/javascript" src="data.js"></script>
<div id="target"></div>
<script type="text/javascript">
var template = ?????? // how do I attach the template?
var html = Mustache().to_html(template, data);
$('#target')[0].innerHTML = html;
</script>
template = $('.template').val();
Where your template is in the DOM...
<textarea class="template">
<h1>{{header}}</h1>
{{#bug}}
{{/bug}}
{{#items}}
{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}
{{#link}}
<li>{{name}}</li>
{{/link}}
{{/items}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}
</textarea>
You could also render multiple templates directly into your page...
<script id="yourTemplate" type="text/x-jquery-tmpl">
{{tmpl "#yourTemplate"}}
<div>Something: ${TemplateValue}</div>
</script>
<div id="example">
</div>
<script type="text/javascript">
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$("#example").append(data);
}
function get() {
var content = $("#example").html();
alert(content);
}
</script>
INSERT
GET
</body>
</html>
what i want to do:
when i click on insert, i want to insert this code into example div:
<script type="text/javascript"> function test() { a = 5; }<\/script>
when i click on get, i want to get that code, which i inserted there.
but when i click on insert, and then on get, there's no code.. where is problem ? thanks
According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.
var enc = $('<div/>').text('<script type="text/javascript"> function test() { a = 5; }<\/script>').html();
$("#example").append(enc);
This works:
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$('#example').text(data);
}
function get() {
var content = $('#example').text();
alert(content);
}
Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.