node.js express传递object给ejs(一)双引号问题

在node.js中,用msnodesql查询sql server数据库,然后传递给ejs模板页:

 

exports.yjUser = function(req, res){
	var sql = require('msnodesql');
	var conn_str = "Driver={SQL Server Native Client 11.0};Server={.\\sql2008};Database={erp};uid=sa;PWD=1234;";
	sql.open(conn_str, 
		function (err, conn) 
		{
    		if (err) 
    		{
        		console.log("Error opening the connection!");
        		return;
    		}
			conn.queryRaw(
				"SELECT UserOID,UserAID,Name FROM Users", 
				function (err, results) 
				{ 
					if (err) 
					{ 
						console.log("Error running query!"); 
						res.end(err);
						return; 
					} 
					
					try
					{
						for (var i = 0; i < results.rows.length; i++) 
						{ 
  							console.log("0:" + results.rows[i][0]); 
						} 
						var s=JSON.stringify(results);					
						res.render('user.ejs',{data:s});	
					}
					catch(e)
					{
						res.end(e);
					}
				}
			);
		}
	);
}

在ejs模板页中,

 

(1)使用locals获取传递过来的参数;

(2)获取参数的tag有讲究,参考:https://github.com/visionmedia/ejs#features

方法1:

var s01 = '<%= locals.data %>';

用等号获取时,会按html转码,如,双引号会转成&quot;,如:

 

方法2:

 

var s02 = '<%- locals.data %>';

用减号获取时,不会转码,如:


(3)没有集成JSON元件,需要引入json2.js才能使用JSON.parse

 

<!DOCTYPE html>
<html>
	<head>
		<style type="text/css" title="currentStyle">
			@import "javascripts/dataTables-1.9.4/media/css/demo_page.css";
			@import "javascripts/dataTables-1.9.4/media/css/demo_table.css";
		</style>
		<script src="javascripts/jquery/jquery-1.10.1.js"></script>
		<script src="javascripts/dataTables-1.9.4/media/js/jquery.dataTables.js"></script>
		<script src="javascripts/json/json2.js"></script>
		<script type="text/javascript">
			var g_data = null;

			$(document).ready(function() {
				var s01 = '<%= locals.data %>';
				var s02 = '<%- locals.data %>';
				var s = "";
				s = s + "-1-" + s01.length;
				s = s + "-2-" + s02.length;
				$('#div_json1').text(s01);
				$('#div_json2').text(s02);

				if (s01 == s02)
					s = s + "-y-";
				else
					s = s + "-n-";
				s = s + "-3-";
				$('#h_name').html(s);

				g_data = JSON.parse(s02);
				s = s + "-4-";
				$('#h_name').html(s);

				$('#dynamic').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
				$('#example').dataTable({
					"aaData" : g_data.rows,
					"aoColumns" : [{
						"sTitle" : "UserOID"
					}, {
						"sTitle" : "用户标识"
					}, {
						"sTitle" : "用户名",
						"sClass" : "center"
					}]
				});
			});
		</script>

	</head>
	<body>		
		<h1>My Name is:</h1>
		<h1 id="h_name"></h1>
		
		<div id="div_json1"></div>
		<br>
		<div id="div_json2"></div>
		<br>
		<div id="div_json3"></div>
		<div id="dynamic"></div>				
	</body>
	<% include foot.ejs %>
</html>

 

 

 

 

 

展开阅读全文

没有更多推荐了,返回首页