工作笔记:ajax json 同一jsp页面中,把java变量赋给js变量,如果java变量字符串符合json格式,则赋给js变量时,js变量会自动的变为json对象

前端之家收集整理的这篇文章主要介绍了工作笔记:ajax json 同一jsp页面中,把java变量赋给js变量,如果java变量字符串符合json格式,则赋给js变量时,js变量会自动的变为json对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
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" "http://www.w3.org/TR/html4/loose.dtd">
<%
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" "http://www.w3.org/TR/html4/loose.dtd">
<%
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" "http://www.w3.org/TR/html4/loose.dtd"> <% 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>

猜你在找的Ajax相关文章