以下是我的JSON回复
{
"status":"success",
"results":[
{
"customer_id":"179",
"customer_name":"satishakarma",
"customer_email":"satish@gmail.com",
"customer_username":"satish",
"customer_mobileno":"9876543210",
"game_amount":"1200"
}
]
}
这是js代码
success:function(e){
var d = JSON.parse(e);
if (d.status === 'success') {
//window.location="game.html";\
var user = (JSON.stringify(d));
console.log(user);
console.log(user.results.customer_name);
//localStorage.setItem(d.customer_name,d.game_amount);
}else
{
alert('Username and Password Invslid');
}
}
我想从响应中获取客户名称
我写了console.log(user.results.customer_name);
来在控制台中打印。但是出现Cannot read property 'customer_name' of undefined
错误。如何从这个api获取客户名称?
答案 0 :(得分:2)
由于您的results
对象中只有一个user
数组,因此您需要使用user.results[0]
访问该数组。
var user = {
"status":"success",
"results":[
{
"customer_id":"179",
"customer_name":"satishakarma",
"customer_email":"satish@gmail.com",
"customer_username":"satish",
"customer_mobileno":"9876543210",
"game_amount":"1200"
}
]
}
console.log(user.results[0].customer_name);
但是,如果results
数组中有多个对象,那么可以在该数组上使用循环:
var user = {
"status":"success",
"results":[
{
"customer_id":"179",
"customer_name":"satishakarma",
"customer_email":"satish@gmail.com",
"customer_username":"satish",
"customer_mobileno":"9876543210",
"game_amount":"1200"
},
{
"customer_id":"180",
"customer_name":"satishakarma2",
"customer_email":"satish2@gmail.com",
"customer_username":"satish2",
"customer_mobileno":"9876543210",
"game_amount":"1200"
}
]
}
user.results.forEach(obj=>console.log(obj.customer_name));
还要确保user
变量具有对象而不是字符串化的JSON。如果这是一个字符串变量,那么你需要将它解析为JSON,否则你将获得Uncaught TypeError: Cannot read property '0' of undefined
var user = `{
"status":"success",
"results":[
{
"customer_id":"179",
"customer_name":"satishakarma",
"customer_email":"satish@gmail.com",
"customer_username":"satish",
"customer_mobileno":"9876543210",
"game_amount":"1200"
}
]
}`;
user = JSON.parse(user);
console.log(user.results[0].customer_name);
答案 1 :(得分:1)
它在阵列中......
console.log(user.results[0].customer_name)
答案 2 :(得分:1)
console.log(user.results[0].customer_name)
答案 3 :(得分:1)
将您的代码更改为
success:function(e){
var d = JSON.parse(e);
if (d.status === 'success') {
//window.location="game.html";\
var user = d;
console.log(user);
console.log(user.results[0].customer_name);
//localStorage.setItem(d.customer_name,d.game_amount);
}else
{
alert('Username and Password Invslid');
}
}
现在您将能够看到正确的结果。 您已经对该对象进行了字符串化,这使得无法使用点运算符进行调用。