eval()和$.parseJSON()注意事项

时间:2023-03-08 17:08:23

在前后端分离大行其道XXX(巴拉巴拉的废话不多讲了)。描述实际应用场景:后台组装数据,返回到前台调用。

刚开始没有注意“后台返回字符串_1”的形式,使用eval()处理。

只是返回了字符串,不是严格意义上的Json格式的字符串。

[{'priceType':'901e78cd-7c02-4c16-91c7-6b376e383e91','name':'张三','sex':'1','mobilephone':'18989898898','cardtype':'00','cardnum':'411234198810153710','email':'18913881546@163.com','tel':'18956114568','cusnum':'18956114568','validdate':'2019-01-04','birthday':'1988-10-15','fax':'025-85212125','address':'是是是','postcode':'','home':''},{'priceType':'fb89db8d-689a-4b3a-9f87-6296b40a89fa','name':'李四','sex':'1','mobilephone':'18989898898','cardtype':'00','cardnum':'411112198810153710','email':'18913881546@163.com','tel':'18956114568','cusnum':'18956114568','validdate':'2019-01-04','birthday':'1988-10-15','fax':'025-85212125','address':'是是是','postcode':'','home':''}]

后台返回字符串_1

在html页面中接受时,直接定义了一个var obj=eval(data.value);obj就是个对象数组,进行接下来的操作。

但是数据结构稍微复杂点后(如“后台返回字符串_2”),单纯的使用eval()则报错,“VM1004:1 Uncaught SyntaxError: Unexpected token :”

eval()和$.parseJSON()注意事项

这时候用eval('('+data.value+')'); 可以取出对象。

{'adult':'1','child':'1','rows':[{'priceType':'901e78cd-7c02-4c16-91c7-6b376e383e91','name':'张三','sex':'1','mobilephone':'18989898898','cardtype':'00','cardnum':'411234198810153710','email':'18913881546@163.com','tel':'18956114568','cusnum':'18956114568','validdate':'2019-01-04','birthday':'1988-10-15','fax':'025-85212125','address':'是是是','postcode':'','home':''},{'priceType':'fb89db8d-689a-4b3a-9f87-6296b40a89fa','name':'李四','sex':'1','mobilephone':'18989898898','cardtype':'00','cardnum':'411112198810153710','email':'18913881546@163.com','tel':'18956114568','cusnum':'18956114568','validdate':'2019-01-04','birthday':'1988-10-15','fax':'025-85212125','address':'是是是','postcode':'','home':''}]}

后台返回字符串_2

$.parseJSON():则需要后台返回严格的json格式的字符串。推荐用http://www.bejson.com检查下。

eval()和$.parseJSON()注意事项

{"adult":"1","child":"1","rows":[{"priceType":"901e78cd-7c02-4c16-91c7-6b376e383e91","name":"张三","sex":"1","mobilephone":"18989898898","cardtype":"00","cardnum":"411234198810153710","email":"18913881546@163.com","tel":"18956114568","cusnum":"18956114568","validdate":"2019-01-04","birthday":"1988-10-15","fax":"025-85212125","address":"是是是","postcode":"","home":""},{"priceType":"fb89db8d-689a-4b3a-9f87-6296b40a89fa","name":"李四","sex":"1","mobilephone":"18989898898","cardtype":"00","cardnum":"411112198810153710","email":"18913881546@163.com","tel":"18956114568","cusnum":"18956114568","validdate":"2019-01-04","birthday":"1988-10-15","fax":"025-85212125","address":"是是是","postcode":"","home":""}]}

后台返回字符串_3

前台调用$.parseJSON(data.value);得到所需要的数据。

总结:

1、不推挤使用eval();它执行其中的的 JavaScript 代码。不安全

2、$.parseJSON()对于返回数据要求更严格,且不会执行脚本;推荐使用。

附两个链接:

1、JavaScript eval() 函数

2、js中eval()和$.parseJSON()的区别和联系以及JSON.stringify()