Getting the contextPath into external JavaScript - javascript

How to access ${pageContext.request.contextPath} of jsp into a external javascript file ?

before the script in which you'll need it, you should be able to include something like this. then access it by variable name.
<script>var myContextPath = "${pageContext.request.contextPath}"</script>
<script src='theScriptINeedContextFor.js'></script>

Related

Django: How to pass python variable value to javascript file?

I've a function in views.py which returns latitude and longitude:
return render(request, 'map.html', {'lat_lng':lat_lng})
and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it.
I tried all below stack answers but none worked for me:
Django Template Variables and Javascript
Passing django variables to javascript
How to use Django variable in JavaScript file?
Passing Python Data to JavaScript via Django
You can take advantage of json_script template tag. In your template do this
{{ lat_lng|json_script:"lat_lng" }}
Then in your javascript file you can access this variable like
const lat_lng = JSON.parse(document.getElementById("lat_lng").textContent);
One simple way to do it is to append the following snippet at the top of your template html file(the one that imports your javascript file):
<script type="text/javascript">
const LAT_LNG = "{{ lat_lng }}"; // Or pass it through a function
</script>
when I try to use lat_lng in separate js file then I'm not able to access it.
You can't use a django template variable in a static file. The static files will be returned in a way that bypasses Django's typical request processing.
Instead, set the variables on data-* attributes on an known HTML element, then get the element, access the attribute and use the value that way.
Be sure when that getting the variable in a script tag is before including the separate js file
Exmple :
<script type="text/javascript">
var variable = "{{myV}}";
</script>
<script type="text/javascript" src="myJsFile.js"></script>

How can add value to vb variable in js code?

I'm try to add a value to my vb variable in my js code, this is my example
<script>
'<%Dim Myvariable As Integer%>' = 201278
</script>
but this doesn't work.
Is there a way to do this?
Declare variable either protected or public:
Protected test As Integer = 201278;
And in .aspx file:
<script>
<%=test.toString()%>
</script>
edit.
that comment doesn't make any sense #JoséGregorioCalderón the example shows that it IS in script tags. If you mean the file is an external JS file, that is a different problem.
You could solve this in two ways.
1) You serve the JS file as an ASPX file to generate parts of it that are dynamic. you'll need to take care of the headers to serve it is text/javascript
2) You write the variable to your HTML as a data attribute and read it into your JS directly.
i.e.
or...very quick pseudo code.
<body id="myBody" data-variable="<%=MyVariable%>">
var bodyElement = document.getElementById('myBody')
alert(bodyElement.dataset.variable);

How to access JSON file in JavaScript?

I have a JSON file as data.json and I have an HTML file with JavaScript embedded in it. I want to access data from the JSON file in a simple HTML(file:///C:/Users/XYZ/Desktop/htmlpage.html) file and NOT in a server-client manner(http://....). I have tried following simple code to import JSON file.
<!DOCTYPE html>
<html>
<body>
<p>Access an array value of a JSON object.</p>
<p id="demo"></p>
<script type="text/javascript" src="F:/Folder/data.json">
var myObj, x;
x = data[0].topic;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
I have read this method of using
<script type="text/javascript" src="F:/Folder/data.json">
on other StackOverflow Questions. But it is not working.
Please tell me the simplest way to access the data in the JSON file.
You could try writing something like this in your JSON file in order to assign the data to a variable:
window.data = JSON.parse('insert your json string here');
You can then access window.data in your page's javascript. You can also omit window. and just assign and/or read from data, which is the same as window.data.
Perhaps a cleaner approach would be to use an AJAX request either with jQuery or vanilla Javascript, both approaches have many answers available on this site.
You could also look into a solution with jQuery.getJSON(): Loading local JSON file
If you are able to use PHP for your desired task (accessing data from JSON file and doing some stuff with data) it will be easier to use PHP to open JSON files. You can use following code to access JSON files.
<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
?>
Here $json will be the outermost object (if file starts with '{') / array (if file starts with '['). Then you can use it in a regular way.
Maybe some of you can think that why I'm posting PHP solution in Javascript question? But I found this very much easier than opening file in Javascript. So if you are allowed to use PHP go with that.

Set an url globally in JavaScript

In an ASP.NET MVC application, we call web service and web API methods from JavaScript files. Whenever the url gets changed, we have to modify the url in many .js files.
As we access the url in JavaScript, is there anyway to set it globally like web.config in .NET?
Thanks.
You can just have this or something similar in your view:
<script>
window.apiUrl = '<%=ConfigurationManager.AppSettings["apiUrl"]%>';
</script>
(or if it's Razor?...)
<script>
window.apiUrl = '#(ConfigurationManager.AppSettings["apiUrl"])';
</script>
That way, your other scripts can simply reference:
var url = window.apiUrl;
You can declare a global variable in the view(call VewBag in the Controller),and This variable in the configuration

Using JavaScript Variables On Different Files

I have a js variable defined in a js file like so :
onlineUsers.js :
var _onlineUsers=new Array();
I'm then linking the js file into index.html like so
<script type="text/javascript" src="onlineUsersVars.js"></script>
and I know for sure it gets a value after awhile since I've checked it with alert .
However , when I try to do the same with another html file , e.g file2.html
then link the js file to get the same variable
file2.html :
<script type="text/javascript" src="onlineUsersVars.js"></script>
and check the value , the value is nothing .
Anyone has a clue what I'm missing ? Do javascript variables 'die' after being linked to one page ? How can I share the same global javascript variable between many html pages ?
You will have to include the script (onlineUsers.js) on every HTML page. And the variable (_onlineUsers) will need to be re-instantiated on every HTML page.
Yeah if you go from file1.html to file2.html, even though you have the same JS file on both files, the values will all clear. The best way to pass variables from page to page would be by using cookies.
Try using HTML5 localStorage to store the variable and then call it each time you need to.
function onlineUsers() {
var _onlineUsers=new Array();
localStorage.onlineUsers = _onlineUsers;
}
Then this value will be available anytime you need it. Although that is client side not server side.

Categories

Resources