我收到的 JSON 响应,
{
"user_data": {
"id": 22,
"first_name": xxx,
"last_name": xxx,
"phone_number": "123456789",
},
"question_with_answers" : [
{
"id": 1,
"question_name": "Features of our project that you like (select one
or more):",
"answers": [
{
"id": 19,
"question_id": 1,
"customer_id": 22,
"option": "Location",
},
{
"id": 20,
"question_id": 1,
"customer_id": 22,
"option": "Architecture",
},
]
},
{
"id": 2,
"question_name": "Features of our project that you DID NOT like
(select one or more):",
"answers": [
{
"id": 22,
"question_id": 2,
"customer_id": 22,
"option": "Location",
},
]
},
{
"id": 3,
"question_name": "How soon are you looking to buy a new home?",
"answers": [
{
"id": 24,
"question_id": 3,
"customer_id": 22,
"option": "Immediately",
}
]
}
]
}
这就是 JSON 响应的样子,现在我需要使用 jquery 显示数据
我的js代码
function openModal(Id){
var CustomerId = Id;
$.ajax({
type : 'get',
url: 'customer-details',
data: {
'CustomerId':CustomerId
},
success: function(data)
{
//what I have to do here
}
})
}
我想要的输出是,
first_name : xxx
last_name : xxx
phone_number : 123456789
1.Features of our project that you like (select one or more):
ans: Location, Architecture
2.Features of our project that you DID NOT like (select one or more)
ans: Location
3.How soon are you looking to buy a new home?
ans: Immediately
这就是我的输出应该是上面 json 响应的样子,是否可以使用我得到的 Json 响应获得上面的输出 我从后端传递了两个变量,例如 user_data 和 Question_with_answers
最佳答案
在成功处理程序中,首先使用
将 json 放入数组中var obj = JSON.parse(data);
现在在数据中你有你的响应数组,你可以像这样使用它
obj.first_name
obj.last_name
注意:- 可能您在 JSON.parse
中遇到问题,所以首先使用
var data = json.stringify(data)
之后使用 Json.parse 函数并使用上面的数据变量 该数据
关于javascript - 在ajax jquery中显示json响应,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45387846/