我需要有人来阐明这个问题。
当一个人进行 AJAX 调用时,会调用一个 php 脚本,该脚本会回显 json_encode 内容,以便 javascript 可以对其进行处理。注意:假设我们在 php 脚本中将 header 设置为 json。
javascript从php脚本接收到的数据,我们是否必须使用eval或json的库来解析它?编辑:是因为它将从 php 文件接收到的数据视为文本而不是 javascript 吗?
我们可以在 php 脚本返回的数据上使用 javascript 点符号吗?或者在我们可以使用点表示法之前,这些数据是否必须以某种方式转换为 JavaScript 对象?
先感谢您。
JSON 只是一个字符串,它恰好符合 Javascript 的对象语法(因此缩写为:JavaScript Object Notation。)
要将其转换为 Javascript 对象,您可以使用 eval 函数,但为了提高安全性,建议使用现代浏览器中包含的 JSON 对象,或您选择的 Javascript 库提供的函数:
var json = '{"thing":1, "thang":"two"}';
var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere
许多库还将作为 Ajax 请求的一部分为您处理转换。 jQuery 是这样实现的:
jQuery.get('http://domain.com/path/to/request', function(obj)
{
// string is automatically converted to an object,
// usable as array or with dot notation
alert(obj.thing);
alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)