我有JSON数据,其中有一些问题,我使用jQuery在屏幕上显示。基于用户的答案,需要向用户显示下一个问题。 请指导我。下面我给出了代码示例
var json = '[
{"QuestionId": 1,Question":"Question Number 1","Answer":"Answer1"},
{"QuestionId": 2,"Question":"Question Number 2","Answer":"Answer2"},
{"QuestionId": 3,"Question":"Question Number 3","Answer":"Answer3"},
{"QuestionId": 4,"Question":"Question Number 4","Answer":"Answer4"},
{"QuestionId": 5,"Question":"Question Number 5","Answer":"Answer5"}
]';
var jsonArray = $.parseJSON(json);
$.each(jsonArray, function(index,jsonObject){
$.each(jsonObject, function(key,val){
console.log("key : "+key+" ; value : "+val);
DisplayQuestionOnUI();
//Based on Answer of first question display next question
//e.g. for question 1 if answer is yes then display question 4 and 5
//otherwise display question 2 then 3
});
});
答案 0 :(得分:0)
首先,你有两次关键的“问题”。因此,第二个值会覆盖第一个值。通过调用第一个“QuestionId”或在id之后调用子对象来解决此问题。 例如:
var json = '[
1:{"Question":"Question Number 1","Answer":"Answer1","NextQuestion":3},
2:{"Question":"Question Number 2","Answer":"Answer2","NextQuestion":5},
3:{"Question":"Question Number 3","Answer":"Answer3","NextQuestion":7},
]';
如果从ajax请求或类似请求获取数据,那么使用json语法也是合乎逻辑的。否则,您应该使用正常的对象初始化。
目前您正在查看所有关键值对。如果答案正确,添加一个新字段“NextQuestion”,其中包含下一个问题ID。然后你想要一个像这样的逻辑:
这可以通过递归或循环来实现。