javascript json的使用(以及中文乱码的解决乱码)

来源:互联网 发布:企业网络整改方案 编辑:程序博客网 时间:2024/05/08 01:17

对于js使用json,首先到官网拷贝json.js文件,地址http://www.json.org/js.html

然后在页面引入即可使用:

<script type="text/javascript" src="json.js"></script>

测试一下能不能用,可以写个jsp页面,然后给按钮加个方法,弹出处理后的json字符串。

对于中文乱码,改变编码方式为:GB2312。

可以在页面直接改,也可以在response返回时改。

页面的改法:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>

java代码response返回改法:

response.setHeader("Cache-Control", "no-cache");
  response.setContentType("text/json;charset=gb2312");



下面看看代码吧,介绍了字符串与json对象相互转化:(本例用到了jquery,只不过调用了一个按钮单击事件,你可以改成onclick)

<%@ page language="java"  pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB2312"><title>Insert title here</title><script type="text/javascript" src="json.js"></script><script type="text/javascript" src="jquery-1.6.2.js"></script><style>  button { margin:4px; cursor:pointer; }  input { margin:4px; color:blue; }  </style></head><body><div>    <button id="button3">json</button>  </div>  <input type="text" value="click a button" /><script>/////////#button3    $("#button3").click(function () {    ///json对象转化成j字符串--toJSONString()///字符串转化成json对象--eval('(' + str + ')');///取json对象里面某个属性的值用点(例如myObject.bindings[0].time) var myJSONObject = {"bindings": [        {"nnn": "春天", "time": "标示", "add": "北京"},        {"ircEvent": "好", "method": "方法", "regex": "上海"}    ] };    alert("json对象取属性值\n"+myJSONObject.bindings[0].nnn );    ///json对象转化成json字符串方法:var myJSONtext=myJSONObject.toJSONString();alert("json对象转化成字符串,toJSONString\n"+myJSONtext);var myJSONtext2=JSON.stringify(myJSONObject);alert("json对象转化成字符串,用全局的内置对象JSON.stringify\n"+myJSONtext2);    ///json字符串转化成json对象方法:var myJSONObject2 = eval('(' + myJSONtext + ')');var myJSONObject3=myJSONtext.parseJSON();var myJSONObject4=JSON.parse(myJSONtext);alert("字符串转化成json对象,用eval\n"+myJSONObject2.bindings[0].time );alert("字符串转化成json对象,用parseJSON\n"+myJSONObject3.bindings[0].add );alert("字符串转化成json对象,用全局的内置对象JSON.parse\n"+myJSONObject4.bindings[0].nnn );    /////////////////    });</script></body></html>   





原创粉丝点击