Home > Web Front-end > JS Tutorial > body text

js/jquery解析json和数组格式的方法详解_javascript技巧

WBOY
Release: 2016-05-16 17:04:49
Original
908 people have browsed it

在解析之前,我们必须弄清楚几个概念:数组,关联数组以及json之间有哪些区别和联系点?

一.概念介绍
1.数组

语法:
ECMAScript v3规定了数组直接量的语法,JavaScript 1.2和JScript 3.0实现了它。可以把—个用逗号分隔的表达式列表放在方括号中,创建并初始化—个数组。这些表达式的值将成为数组元素。例如:

var a = [1, true, 'abc'];

具体操作查看API.

ps:必须方括号隔开。

2.关联数组

1.语法:
var myhash= {”key1″:”val1″, “key2″:”val2″ };//obj

2.var
myhash= {key1:”val1″, key2:”val2″ };//obj-也可以

ps:跟json格式几乎相同,但是json格式要求更加严格(里面的键值对必须使用双引号),但json只能作为一种格式标准,如果要对其进行操作必须转换成关联数组对象(obj)。

2.简单操作
1.向Hash关联数组添加键值

// 添加一个新键 newkey ,键值为 newval

myhash[”newkey”] = “newval”;

2.删除Hash关联数组已有键值

// 删除一个键 newkey ,同时,该键值对应的 newval 也就消失了
delete myhash[”newkey”];

3.遍历Hash关联数组

// 遍历整个hash 数组
for (key in myhash) {
val = myhash[key];
}

4.获得值

方式1.myhash.key1
方式2.myhash.key2

3.json
格式要求:

{”key1″:”val1″, “key2″:”val2″ };//严格按照此格式,操作可依照关联数组的操作

二.前后台交互中几个关键点
1.当服务器发送的数据不是一条json,而是多条json时,则应当联系数组和关联数组来组装字符串
例如:var objs = [{ id: 1, name: 'n_1' }, { id: 2, name: 'n_2'}];

2.至始至终服务器给客户端的数据都只是字符串,因此为了让其能够在js中对其进行必要的操作,可以通过eval()进行转换成js可执行的对象。
因此jQuey中提供的$.parseJSON()是有局限的,如果是上面1提到的这种情况则就必须使用eval()进行转换,然后再通过$.each(objs,function(i,o){...})进行操作

三.具体的实例代码
页面代码:

复制代码 代码如下:


 
 

 

后台代码:
复制代码 代码如下:

@Override
 protected void service(HttpServletRequest req, HttpServletResponse reps)
   throws ServletException, IOException {
  Map jsonMap=new HashMap();
  jsonMap.put("name", "techbirds");
  jsonMap.put("age", 23);
  jsonMap.put("sex", "male");
  reps.getWriter().print(JSONObject.fromObject(jsonMap).toString());
  reps.getWriter().flush();
  reps.getWriter().close();

 }

复制代码 代码如下:

 @Override
 protected void service(HttpServletRequest req, HttpServletResponse reps)
   throws ServletException, IOException {
  String array="[1,2,3,4,5,6]";
  reps.getWriter().print(array);
  reps.getWriter().flush();
  reps.getWriter().close();

 }
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!