Цитата:
$(function(){
var vote = {};
var index = 0;
var item;
$('#ok').click(function(){
$.get(pathToPolls, function(data) {
item = JSON.parse(data);
answers(); //выводим блоки с вопросами
});
if(index) {
vote['id']= item[index]['id'];
vote['question']=item[index]['question'];
vote['answers']=item[index]['answers'];
show_answers(); //показываем блок с вопросами
}
else {
vote['id']= item[index]['id'];
vote['question']=item[index]['question'];
vote['answers']=item[index]['answers'];
show_answers();
index++;
}
});
});
|
giwuf,
зачем вам vote ? |
рони и Nexus, спасибо большое за помощь - изучу и постараюсь внедрить!
|
giwuf,
item = JSON.parse(data); ??? это jquery, data уже обьект , а не строка. item = data; |
Цитата:
А в случае с примером от Nexus Цитата:
const data = [{
"id": "1",
"question": "Какую марку предпочитаете?",
"answers": ["honda", "bmw", "volvo"]
}, {
"id": "2",
"question": "Цвет авто?",
"answers": ["black", "red", "blue"]
}];
И теперь вытащить данные с настоящего файла json, как было раньше не удается. Так:
$.get(data.json, function(data) { });
Или так
$.getJSON(data.json, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
});
Показывает ошибку и данные не подтягиваются. Снова что-то недопонимаю? Иои нужно константу сохранять как файл json и подключать так и потом парсить? <script type="text/javascript" src="file.json"></script> |
Цитата:
Цитата:
|
giwuf,
<form id="vote" action="#" method="POST">
<div id="content">
<div class="pattern">
<h4 class="question">{% question %}</h4>
<div class="answers">
<div class="radio"><label><input type="radio" name="poll[{% id %}]" value="{% answer.value %}">{% answer.title %}</label></div>
</div>
</div>
</div>
<div><button type="submit" class="btn btn-default">Ответить</button></div>
</form>
<script>
$.getJSON('/path/to/you-json',function(data){
data=(typeof data==='string')?JSON.parse(data):data;
const content = document.getElementById('content');
const patternNode = content.querySelector('.pattern');
patternNode.classList.remove('pattern');
const pattern = patternNode.outerHTML;
patternNode.parentNode.removeChild(patternNode);
data.forEach(function(question, index) {
content.insertAdjacentHTML('beforeEnd', pattern.replace(/{%\s?question\s?%}/gim, question.question));
const questionNode = content.lastChild;
questionNode.dataset.index = index;
questionNode.style.display = 'none';
const answers = questionNode.querySelector('.answers');
const answer = answers.querySelector('.radio').outerHTML;
answers.innerHTML = question.answers.map(function(title, value) {
return answer
.replace(/{%\s?id\s?%}/gim, question.id)
.replace(/{%\s?answer.title\s?%}/gim, title)
.replace(/{%\s?answer.value\s?%}/gim, value);
}).join("\n");
});
let currentQuestionIndex = 0;
const questions = [].slice.call(content.querySelectorAll('[data-index]'));
questions[0].style.display = 'block';
document.querySelector('#vote [type="submit"]').addEventListener('click', function(e) {
questions[currentQuestionIndex].style.display = 'none';
if (++currentQuestionIndex >= questions.length)
return;
e.preventDefault();
questions[currentQuestionIndex].style.display = 'block';
});
});
</script>
|
:-? одно name на все блоки?
|
О, Nexus и рони, спасибо большое! Готов расцеловать!
Расставлю плюсы как только откроется у меня такая возможность. 2 последних мини-вопроса: 1 - выбранные ответы на вопросы на каждой итерации передается в файл, который укажу в форме в поле action="" или как-то по другому 2 - чтобы добавить нумерацию вопросов по id из файла - мне нужно
data.forEach(function(question, index) {
//приплюсовать к заголовку вопроса параметр index - так?
});
|
Цитата:
|
| Часовой пояс GMT +3, время: 04:14. |