I have a small Python script which is supposed to send a string to the javascript in my HTML file to be rendered on the page. However, the script is not receiving the data sent to it from the Python file. My code is below:
simple.html:
<html>
<body>
<h1>Hello</h1>
<p1 id="demo"></p1>
<script>
var s = {{to_display}};
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
main.py:
from bottle import Bottle, template
app = Bottle()
#app.route('/')
def index():
data = {"to_display":"HI, how are you"}
return template("simple.html", data)
if __name__ == '__main__':
app.run()
I would like the page to look like this:
Hello
HI, how are you
Unfortunately, it is only displaying:
Hello
Does anyone know how to correct this issue?
The problem here is that the template is not rendering valid javascript.
>>> from bottle import template
>>> data = {'to_display': 'HI, how are you'}
>>> rendered = template('/home/kev/tmp/test.html', data)
>>> print rendered
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = HI, how are you;
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
Loading this html in the browser raises a syntax error (tested on Firefox 52.3.0):
SyntaxError: missing ; before statement
The problem is that the definition of s is not quoted within the <script> tag. Fixed version:
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = "{{ to_display }}";
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
Renders to this markup, which works as expected in the browser:
>>> print rendered
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = "HI, how are you";
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
Related
I'm making javascript call python result, but the new data not came back from .py script / or document.getElementById("demo").innerHTML not activate
environment: windows, python, and I open with live server in visual studio code
<!DOCTYPE html>
<html>
<body>
<p id="demo">original data</p>
<script type="text/javascript">
const spawner = require('child_process').spawn;
const data_to_pass_in ={
data_sent:'Send this to python script',
data_returned: undifined
};
console.log('Data sent to py script:', data_to_pass_in);
const python_process = spawner('python',['./get_sql_where_02.py', JSON.stringify(data_to_pass_in)]);
python_process.stdout.on('data',(data)=>{
console.log('Data receive from py script:',JSON.parse(data.toString()));
});
document.getElementById("demo").innerHTML = data_to_pass_in;
</script>
</body>
</html>
get_sql_where_02.py
import mysql.connector
import webbrowser
import time
import pymysql
import sys
import ast
mydb = mysql.connector.connect(
host="196.8.98.141",
user="root",
password="password",
database="data_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_PRODUCT FROM webpage WHERE P_ID = '001'")
myresult = mycursor.fetchall()
print(myresult)
data_to_pass_back = myresult
result picture
I just learn js for few hour so maybe is a simple question, that I need javascript call python result on web
Just join to this community. I have python script that produce string in html :
from shelljob import proc
import flask
import os
import eventlet
eventlet.monkey_patch()
app = flask.Flask(__name__)
#app.route('/create')
def create():
g = proc.Group()
p = g.run("timeout 30s mycommand | grep -Eo 'https?://\S+'")
def read_process():
while g.is_pending():
lines = g.readlines()
for proc, line in lines:
yield "data:" + line + "\n\n"
return flask.Response( read_process(), mimetype= 'text/event-stream' )
#app.route('/')
def get_page():
return flask.send_file('page.html')
if __name__ == '__main__':
app.run(debug=True)
that code will produce something like :
This sample output with static result...
Please visit https://www.example.com/click?nonce=1a2b3c4d to bla bla bla.
This sample output with static result...
Please visit https://www.example.com/click?nonce=1a2b3c4d to bla bla bla.
How i can get url only like this one and only show first result :
https://www.example.com/click?nonce=1a2b3c4d
because if i type"timeout 30s mycommand | grep -Eo 'https?://\S+'" i can get exact url.
I can replace the text with javascript, but i'm still got list result instead 1 line. This my html "page.html"
<!DOCTYPE html>
<html>
<head>
<style type="text/css">.urldb{color: #ffffff;padding: 10px;background: red;text-decoration: none;}</style>
</head>
<body>
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-linkify/2.1.4/linkify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-linkify/2.1.4/linkify-string.min.js"></script>
<script>
var source = new EventSource("/create");
var options = {className: 'urldb',target: {url: '_blank'}};
source.onmessage = function(event) {
document.getElementById("output").innerHTML += event.data.replace(/(\bhttps?:\/\/\S+)|[^]/g, '$1').linkify(options) + "<br/>";
if (event.data.indexOf('Welcome') > -1) {
$("#output").hide();
window.location.href = "https://example.com";
}
};
</script>
</body>
</html>
Using that script i got result like :
https://www.example.com/click?nonce=1a2b3c4d
https://www.example.com/click?nonce=1a2b3c4d
https://www.example.com/click?nonce=1a2b3c4d
Thanks and sorry if any wrong in my question.
Edit to add more alternative wrong in python or javascript and remove "e" to make clear.
You have maybe typo in the pattern. Change https?://e\S+ to https?://\S+ (remove e) and it works.
For output only fist match you can use -m1. For more informations see man page.
<html>
<head>
<script type="text/javascript">
function open_urls() {
var url1="https://finance.yahoo.com/";
var newpage=window.open(url1);
alert(newpage.document.body.innerText.split(' ').length);
}
</script>
</head>
<body onload="javascript: open_urls()"></body>
</html>
The code above did not work, how to access DOM for a different URL?
I'd like to open an URL and show the word count of that URL.
You can't simply open another window and page and expect to have access to it. The web follows many security policies to prevent operations like this, such as the Same-Origin policy. Long-story short, you can't access URLs that don't fall under the same-origin as the page you're calling from. You couldn't therefore access Yahoo finance in your example (most likely).
If you were calling from the same origin, you could use an API like fetch to get just the text and do a word count there, or you could even load an iframe and query that: myIframe.contentWindow.document.body.innerHTML.
So knowing that you cannot do this from the browser, you could do it from a NodeJS application (perhaps also using fetch):
var fetch = require('node-fetch');
fetch('https://finance.yahoo.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
// perform word-count here
});
I understand that you were hoping to do this from the browser, but unfortunately you will not be able to do so for origins that you do not control.
You can try this out.
In you index.html (suppose) write this:
<html>
<head>
<title>Index Page</title>
</head>
<script type="text/javascript">
function poponload()
{
testwindow = window.open("new_window.html", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
}// here new_window.html is file you want to open or you can write any url there
</script>
<body onload="javascript: poponload()">
<h1>Hello this can Work</h1>
</body>
</html>
And suppose your new_window.html is like this:
<html>
<head>
<script>
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
function run_this(){
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
alert(count);
}
</script>
</head>
<body onload='javascript: run_this()' id="content">
<h1>This is the new window</h1>
</body>
</html>
I Have edited the code, the updated code is below, This code is not able to fetch the keywords meta tag, hence it is not working.
old description: I am trying to concatinate the strings to get the finalUrl, but I am not able to do so becuase of the tags variable. I need to fetch the keywords meta tag of the page and append it to get the finalUrl. Any help?
<script type="text/javascript">
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/details/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
function loadJSON(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
}
function showGameDetail(feed){
var title = feed.title;
var game_url = feed.pscomurl;
var packart_url = feed.Packart;
$("#bnr-ads-box").html("<img src='"+"http://abc.com/"+packart_url+"'>");
}
loadJSON(finalUrl);
</script>
<div id="bnr-ads-box"></div>
<!DOCTYPE html>
<html>
<head>
<meta id="metaK" name="keywords" content="customizable software for QuickBooks, QuickBooks-integrated, Method customization, CRM accounting, Method for QuickBooks, Method CRM, Method blog, Salesforce automation, Method online platform, QuickBooks customization, web-based platform, industry-specific, customer portal, Method Field Services, Method Manufacturing, ERP" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
document.getElementById("demo").innerHTML=finalUrl;
}
</script>
</body>
</html>
change this
var tags="$('meta[name=keywords]').attr("content");";
to
var tags=$('meta[name=keywords]').attr("content");
also use this code var finalUrl = gameurl + tags + jsn;
What you need is to escape the double quotes inside your tags variable, like so:
var tags="$('meta[name=keywords]').attr(\"content\");";
Cris' solution is also fine, but in some case you will need to have two sets of double quotes inside a string so you will be forced to do escaping correctly.
FYI: Escaping is the process of having special characters getting generated in a string which would otherwise cause issues, for instance in javascript you can't have newlines in a string, like this:
var mystring = 'on
a different line'; // <- this causes a syntax error
So one would do the following:
var mystring = 'on\na different line';
You forgot to include the jquery
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="hello"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
alert(finalUrl);
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Tough debatable, you can use an array, which can be concatenated by calling join():
var tags = $('meta[name=keywords]').attr("content");
var data = [
"http://xyz/abc/names/",
encodeURIComponent(tags),
".json?callback=showGameDetail"
].join('');
$("#demo").html(data);
Actually the concat method works on strings too (in chrome at least) but the recommended method is using the plus concatenation string operator
You are however missing some stuff
jQuery library - I assume you want that since you have $(...) in the example
encoding of the string from the keywords - I use encodeURIComponent to handle possible newlines and quotes in the keywords
.
<!DOCTYPE html>
<html>
<head>
<title>Create a URL from keywords</title>
<meta name="keywords" content="These are tags" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function myFunction() {
var tags = $('meta[name=keywords]').attr("content");
var URL ="http://xyz/abc/names/" +
encodeURIComponent(tags) +
".json?callback=showGameDetail";
window.console && console.log(URL);
$("#demo").html(URL);
}
</script>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>