工作笔记:ajax json 同一jsp页面中,把java变量赋给js变量,如果java变量字符串符合json格式,则赋给js变量时,js变量会自动的变为json对象
发布日期:2021-09-22 22:46:59 浏览次数:0 分类:技术文章

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%
 String s="{source_type_code:'2',source_type_name:'电话赠险成功'}";
%>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 bindData();
});
function bindData(){
 var a="<%=s%>";//必须是双引号,不能是单引号
 alert(a);
}
</script>
------------------------------------------------输出:{source_type_code:'2',source_type_name:'电话赠险成功'},加了双引号传的是字符串
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%
 String s="{source_type_code:'2',source_type_name:'电话赠险成功'}";
%>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 bindData();
});
function bindData(){
 var a=<%=s%>;
 alert(a);
}
</script>
------------------------------------------------输出:object Object,不加双引号传的是对象
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%
 String s="{source_type_code:'2',source_type_name:'电话赠险成功'}x";
%>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 bindData();
});
function bindData(){
 var a="<%=s%>";
 alert(a);
}
</script>

------------------------------------------------输出{source_type_code:'2',source_type_name:'电话赠险成功'}x,加了双引号传的是字符串
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%
 String s="{source_type_code:'2',source_type_name:'电话赠险成功'}x";
%>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 bindData();
});
function bindData(){
 var a=<%=s%>;
 alert(a);
}
</script>
----------------------------------------不输出,会报错,如果不加双引号,应该输出对象的,但s串不是符合格式的字符串,必须符合json格式的字符串才能转化为对象传给js变量
java代码片段在服务器端运行,运行生成的结果放在生成的静态页面中再发送到用户浏览器端,浏览器再运行js代码,比如:
<script   language= "javascript ">
      var a= "<%out.print( "hello ");%>";
</script>
实际上到了用户浏览器端就会执行:
<script   language= "javascript ">
      var   a= "hello ";
</script>

 

上一篇:工作笔记:单例模式的作用好处和代码
下一篇:工作笔记:mysql