I need to know how to pass server side object as parameter to javascript function in javascript and ejs
I have header file, onclick function generate url but I need to pass serverside object as parameter to function
server.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
var obj ={"contact" : "fs-xi-fs-men", "aboutus" : "guan-yu-men"}
res.render('index.ejs', {lang: obj});
})
header.ejs
<a class="nav-link" href="javascript:" onclick="redirect('about-us')">About Us</a> // pass server side obj i.e redirect(lang)
<a class="nav-link" href="javascript:" onclick="redirect('contact')">Contact Us</a>
helper.js
function redirect(path){ // pass serverside object to function in js
var urlpath = window.location.origin+"/"+en+"/"+path; //www.abc.com/en/fs-xi-fs-men
window.location.href = urlpath;
}
tried using
//index.ejs
<%- include('header', {tr: lang}) %> //not working
This is what I usually do
Embed your server-side variable/object in the HTML by attaching it to a hidden input value. Also, don't forget to stringify it.
In your javascript, grab that input value, parse it back into an object and now you are able to use it in your javascript code!
<html>
<input id="lang-input" type="hidden" value="<%= JSON.stringify(lang) %>">
<!-- Include JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// wait for HTML to fully load
$(function() {
// grab lang variable
var lang = JSON.parse($('#lang-input').val());
// now you have lang object and can do whatver you want!
});
</script>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.