Javascript 无法读取属性';客户名称';JSON中未定义的
下面是我的JSON响应Javascript 无法读取属性';客户名称';JSON中未定义的,javascript,jquery,json,Javascript,Jquery,Json,下面是我的JSON响应 { "status":"success", "results":[ { "customer_id":"179", "customer_name":"satishakarma", "customer_email":"satish@gmail.com", "customer_username":"satish", "customer_mobileno"
{
"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\u name)代码>以在控制台中打印。但是获取无法读取未定义的属性“customer\u name”
错误。如何从此api中获取客户名称?它位于一个数组中
console.log(user.results[0].customer_name)
因为,您的user
对象中只有一个results
数组,您需要使用user.results[0]
访问该数组
var user={
“状态”:“成功”,
“结果”:[
{
“客户id”:“179”,
“客户名称”:“satishakarma”,
“客户电子邮件”:satish@gmail.com",
“客户用户名”:“satish”,
“客户_mobileno”:“9876543210”,
“游戏金额”:“1200”
}
]
}
console.log(user.results[0]。客户名称)代码>控制台.log(用户.结果[0].客户名称)
将代码更改为
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');
}
}
现在您将能够看到正确的结果。
您已字符串化了对象,因此无法使用点运算符进行调用。结果是一个数组,因此您需要user.Results[0]。customer\u name
tryconsole.log(user.Results[0]。customer\u name)代码>由于当您字符串化时,结果是数组,因此您将对象转换为字符串。当然,字符串没有results
属性。@CertainPerformance。那么在这种情况下我该怎么办?。我是新手this@CertainPerformance谢谢删除stringify后,它可以工作。您的对象是否真正命名为user
?您没有提供足够的代码来确定这一点。@SagarKodte检查了我答案中的第三个片段。这应该是你的解决方案