I have some javascript code which requires few fields from server side. I would like to store this code in a separate .js file but, moustache will not be able to populate it with server side information. This is what I have:
<body>
<script type="text/javascript" src="/js/test.js"></script>
</body>
My .js file:
var testField = '{{someValue}}';
alert(testField); // is null
Thank you
You can try to use eval js function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
var testTemplate = '{{someValue}}';
var testTemplateValue = Mustache.render(testTemplate, view);
var testField = eval(testTemplateValue);
alert(testField);
Eval function is not secure, so you must take care about input manually.
Related
I'm trying to create a chrome extension, with the main code being in python but I'm struggling. I've succeeded in sending information from the user inputted from the HTML side to the python script, but not the other way around. Here's what I have so far (or the code that seems to be the problem):
Python:
#app.route('/get_data', methods = ['POST'])
def get_data():
taken = request.get_data()
taken2 = taken.decode()
print(taken2)
strength = int(taken2) #this works, I use this later in the code
my_variable = 5 #just for example
return jsonify(my_variable), 200
background.js (javascript)
function myAction(input) {
console.log("input value is : " + input.value);
newish = input.value
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
xxhttp.send(newish);
//so sending newish here works, this shows up on my python console (strength becomes this)
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<script src="background.js" type="text/javascript">
</script>
</head>
<body>
<h1>A Thing!</h1>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>User input please? : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html> stuff
What I'm aiming for is for the my_variable to be accepted into the javascript file somehow, and then the html being able to access and display the contents of my_variable. I've tried looking around, but nowhere seems to have the exact thing I'm looking for (send python variable to separate html file for chrome extension). I'm at a bit of a loss, any help would be greatly appreciated, thanks!
Better way of doing it
Since you want to send the variable from python to html by reading the file, this is better than using the FS module in javascript.
example index.html code:
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}</p>
</body>
python code for the above:
newFileCode = open("index.html", "r").read().format(first_header='goodbye',
p1='World',
p2='Hello')
open("index.html", "w").write(newFileCode)
output in the HTML file:
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World</p>
</body>
read more about file handling in python here
PREVIOUS ANSWER
You can parse the data using JSON. Although, you'll need a new Node.js module fs https://nodejs.org/api/fs.html.
Once you've installed that module, you have to maintain two JSONs, one being a JS variable and the other being an external .json file.
Use this code to write in external JSON files in javascript:
fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));
Use this code to read an external JSON file in javascript:
JSON.parse(fs.readFileSync(name).toString())
To get/read the data from the external JSON file in python use this code:
import json
# Opening JSON file
f = open('fileName.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
You can edit the file from javascript and can read it in python using a while loop
I have a razor code which is using resorces from resources.resx. When i use it in a function (java script), it shows error as "unterminated string literal". How do I use resources in my java script code? However in html part of my code it is able to get the actual value if #mynamespace.name
function check(arg)
{
...
var name = "#mynamespace.name";
...
}
You can't use Razor in javascript file, because javascript files are static. All you can do is use script section in your .cshtml file. You can make a walk-around following jcreamer898 post https://stackoverflow.com/a/9406739/4563955
// someFile.js
var myFunction = function(options){
// do stuff with options
};
// razorFile.cshtml
<script>
window.myFunction = new myFunction(#model.Stuff);
// If you need a whole model serialized then use...
window.myFunction = new myFunction(#Html.Raw(Json.Encode(model)));
</script>
I need to read, inside a page of an epub3 book, the contents of one of the file of that same epub, being some data to process with a javascript function.
Unfortunately, Javascript prevents from loading local files for security reasons. (e.g the File API only allows loading uploaded user files).
But for me in the context of an epub3, it makes sense and I didn't find any information in the IDPF EPUB3 documentation related to this topic.
Any idea ?
OK. Let's clarify:
I have an epub3 with the following structure:
<root>
META-INF
...
OEBPS
pages
page.xhtml
data
data.xml
In page.xhtml, I want to write in Javascript something like:
<script type="text/javascript">
//pseudo code
var indata = readAsText("../data/data.xml"); // how to write that ???
var outdata = myfunction(indata);
</script>
Found the solution for ages, and realized that it had never been answered:
So answering to my own question ;-)
<script type="text/javascript">
/* Load the file using HTTP GET */
$.get( "../data/data.xml", function( indata ) {
var outdata = myfunction(indata);
}, 'text');
</script>
In this simple example...
http://plnkr.co/edit/78ObAiirrSFPcvyiBKqn
...I try to have a Handlebars template and the content that should populate it into separate files, instead of having the template inside the HTML and the content object in the js script, as in this other example:
http://embed.plnkr.co/KXdVgedRA8K95S17peuH/
And I also found this post where this guy means the same as I do (right?):
Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
I tried that (what's on the accepted answer, see the code below), but it doesn't work. I get "undefined is not a function".
On the other hand, that answer has 90 upvotes so I must be missing something somewhere. Could someone point that out to me?
Another related question: should I use AJAX to load a local file?
index.html
<script src="cities.tmpl.js"></script> <!-- compiled template -->
<script src="content.js"></script>
<script src="script.js"></script>
script.js
var template = Handlebars.templates['cities.tmpl']; // your template minus the .js
var context = data_pr.all(); // your data
var html = template(context);
Solved it, based on this post:
http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
I changed a little bit so it's easier to read (at least for me):
function getTemplate(path, callback) {
$.ajax({
url: path,
success: function(data) {
var template = Handlebars.compile(data);
if (callback) callback(template);
}
});
}
getTemplate('cities.tmpl', function(template) {
var html = template(data_pr); // data_pr = my data from content.js
document.getElementById('cities-placeholder').innerHTML = html;
});
sample code here
wondering how I can pass a variable from load js like:
<script type="text/javascript" src="script.js?myVar=myValue"></script>
and use and pass to script.js itself?
I Know about declare variable before, but I'm looking for url way.
Thanks in advance.
The javascript wont have access to that value. The server would have to look for that and insert that value into the rendered javascript on your behalf.
Usually though, the pattern is more like this:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
ObjFromScript.myVar = 'myValue';
ObjFromScript.doStuff();
</script>
You'd have to locate the <script> tag in the document and extract the arguments. A prominent example of a site using this is facebook with the #xfbml=1 hashtag.
However, the proper/nice way is not putting any code but functions in script.js and then call someFunction(myValue);.
You could do it on the client or the server. On the client, get hold of the script element and parse the src attribute.
<script id="myScript" src="script.js?myVar=foo"></script>
<script>
var s = document.getElementById('myScript');
s.src; // parse it and extract myVar
</script>
On the server, setup routes so that script.js goes to some handler written in a server-side language like PHP. In that case you could be outputting script.js dynamically. Here's an example in PHP.
script.js => script.php
<?php
header('Content-Type: application/javascript');
$myVar = $_GET['myVar'];
?>
// optionally expose myVar inside JavaScript
var myVar = <?php json_encode($myVar) ?>;
// regular JavaScript
alert(myVar);
var x = 10;
You could use document.currentScript, but it isn't widely supported.
var matches = document.currentScript.src.match(/\?myVar=([^&]+)/),
myVarParam = matches && matches[1];
Alternatively, you could try getting the script element with the matching URL and parse out the GET param.
var scriptPath = 'path/to/this/script.js',
matches = $('script[src^="' + scriptPath + '"]').attr('src').match(/\?myVar=([^&]+)/),
myVarParam = matches && matches[1];