我无法在代码中解决此问题,有人可以解释我的错误/错误吗?
我正在用php创建一个数组,然后通过.getJSON(已编码)发送给javascript。.
for (var i = 0; data['contacts'].length; i++) {
var cont = data['contacts'][i][0];
var name = data['contacts'][i][1];
var p1 = data['contacts'][i][2];
var p2 = data['contacts'][i][3];
var email = data['contacts'][i][4];
var active = data['contacts'][i][5];
$("#cont_"+pos).val(name);
$("#phone1_"+pos).val(p1);
$("#phone2_"+pos).val(p2);
$("#email_"+pos).val(email);
}
当我在JavaScript中收到它时,它崩溃了...
$.getJSON
我收到此错误:未捕获的TypeError:无法读取未定义的属性'0'
我正在使用函数{"contacts":
[["1","David1","32423423","234324","ddd@hotmail.com","1"],
["2","David2","546567","68678767","dsasdas@hotmail.com","0"],
["3","David3","345345","78987","3david@hotmail.com","0"],
["4","David4","434d3455","978987","4david@hotmail.com","0"]]}
,我从PHP得到此响应:
(4) [Array(6), Array(6), Array(6), Array(6)]
0: (6) ["1", "David1", "32423423", "234324", "ddd@hotmail.com", "1"]
1: (6) ["2", "David2", "546567", "68678767", "dsasdas@hotmail.com", "0"]
2: (6) ["3", "David3", "345345", "78987", "3david@hotmail.com", "0"]
3: (6) ["4", "David4", "434d3455", "978987", "4david@hotmail.com", "0"]
length: 4
__proto__: Array(0)
并使用控制台登录javascript:
webpack.config.js
答案 0 :(得分:0)
您的包含JSON的响应可能缺少application/json
标头,因此浏览器不知道如何进行转换。
确保首先var data = JSON.parse(data)
,然后console.log(data)
,以确保一切都按预期进行,然后才开始对它进行操作
如果您使用jQuery的$.ajax()
,请确保在其选项中包含dataType: 'json'
,然后不必担心自己解析。
我通常采取的步骤:
header('Content-Type', 'application/json')
在输出json的页面上JSON.parse(data)
将其转换为对象,前提是json在语法上正确,可以通过确保JSON.parse()
不返回false