2017-05-09 8 views
2

Grundsätzlich habe ich ein Formular, das einfache Fragen stellt und der Benutzer kann entweder in einer Auswahl, Textbox oder Textarea antworten.Wie füge ich ein Bild in eine JSON-Datei ein?

Ich verwendete JSON, um die Fragen zu analysieren.

Allerdings muss ich wissen, wie kann ich ein Bild über die Frage, wie diese ein: http://prntscr.com/f5o8fc

Hier ist meine jQuery:

survey = { questions: undefined, 
      firstQuestionDisplayed: -1, 
      lastQuestionDisplayed: -1}; 

(function (survey, $) { 

    survey.setup_survey = function(questions) { 
     var self = this; 
     this.questions = questions; 

     this.questions.forEach(function(question) { 
      self.generateQuestionElement(question); 
     }); 

     $('#backBtn').click(function() { 
      if (!$('#backBtn').hasClass('disabled')) { 
       self.showPreviousQuestionSet(); 
      } 
     }); 

     $('#nextBtn').click(function() { 
      var ok = true; 
      for (i = self.firstQuestionDisplayed; i <= self.lastQuestionDisplayed; i++) { 
       if (self.questions[i]['required'] === true && !self.getQuestionAnswer(questions[i])) { 
        $('.question-container > div.question:nth-child(' + (i+1) + ') > .required-message').show(); 
        ok = false; 
       } 
      } 
      if (!ok) 
       return 

      if ($('#nextBtn').text().indexOf('Continue') === 0) { 
       self.showNextQuestionSet(); 
      } 
      else { 
       var answers = {res: $(window).width() + "x" + $(window).height()}; 
       for (i = 0; i < self.questions.length; i++) { 
        answers[self.questions[i].id] = self.getQuestionAnswer(self.questions[i]); 
       } 

       $.ajax({type: 'post', 
         url: 'http://localhost:7000/answers', 
         contentType: "application/json", 
         data: JSON.stringify(answers), 
         processData: false, 
         success: function(response) { 
          self.hideAllQuestions(); 
          $('#nextBtn').hide(); 
          $('#backBtn').hide(); 
          if ('success' in response) { 
           $('.completed-message').html('Thank you for participating in this survey!<br><br>'+response['success']); 
          } 
          else if ('error' in response) { 
           $('.completed-message').text('An error occurred: '+response['error']); 
          } 
          else { 
           $('.completed-message').text('An unknown error occurred.'); 
          } 
         }, 
         error: function(response) { 
          self.hideAllQuestions(); 
          $('#nextBtn').hide(); 
          $('#backBtn').hide(); 
          $('.completed-message').text('An error occurred: could not send data to server'); 
         } 
       }); 
      } 
     }); 

     this.showNextQuestionSet(); 

    } 

    survey.getQuestionAnswer = function(question) { 
     var result; 
     if (question.type === 'single-select') { 
      result = $('input[type="radio"][name="' + question.id + '"]:checked').val(); 
     } 
     else if (question.type === 'single-select-oneline') { 
      result = $('input[type="radio"][name="' + question.id + '"]:checked').val(); 
     } 
     else if (question.type === 'text-field-small') { 
      result = $('input[name=' + question.id + ']').val(); 
     } 
     else if (question.type === 'text-field-large') { 
      result = $('textarea[name=' + question.id + ']').val(); 
     } 
     return result ? result : undefined; 
    } 

    survey.generateQuestionElement = function(question) { 
     var questionElement = $('<div id="' + question.id + '" class="question"></div>'); 
     var questionTextElement = $('<div class="question-text"></div>'); 
     var questionAnswerElement = $('<div class="answer"></div>'); 
     var questionCommentElement = $('<div class="comment"></div>'); 
     questionElement.appendTo($('.question-container')); 
     questionElement.append(questionTextElement); 
     questionElement.append(questionAnswerElement); 
     questionElement.append(questionCommentElement); 
     questionTextElement.html(question.text); 
     questionCommentElement.html(question.comment); 
     if (question.type === 'single-select') { 
      questionElement.addClass('single-select'); 
      question.options.forEach(function(option) { 
       questionAnswerElement.append('<label class="radio"><input type="radio" value="' + option + '" name="' + question.id + '"/>' + option + '</label>'); 
      }); 
     } 
     else if (question.type === 'single-select-oneline') { 
      questionElement.addClass('single-select-oneline'); 
      var html = '<table border="0" cellpadding="5" cellspacing="0"><tr><td></td>'; 
      question.options.forEach(function(label) { 
       html += '<td><label>' + label + '</label></td>'; 
      }); 
      html += '<td></td></tr><tr><td><div>' + question.labels[0] + '</div></td>'; 
      question.options.forEach(function(label) { 
       html += '<td><div><input type="radio" value="' + label + '" name="' + question.id + '"></div></td>'; 
      }); 
      html += '<td><div>' + question.labels[1] + '</div></td></tr></table>'; 
      questionAnswerElement.append(html); 
     } 
     else if (question.type === 'text-field-small') { 
      questionElement.addClass('text-field-small'); 
      questionAnswerElement.append('<input type="text" value="" class="text" name="' + question.id + '">'); 
     } 
     else if (question.type === 'text-field-large') { 
      questionElement.addClass('text-field-large'); 
      questionAnswerElement.append('<textarea rows="8" cols="0" class="text" name="' + question.id + '">'); 
     } 
     if (question.required === true) { 
      var last = questionTextElement.find(':last'); 
      (last.length ? last : questionTextElement).append('<span class="required-asterisk" aria-hidden="true">*</span>'); 
     } 
     questionAnswerElement.after('<div class="required-message">This is a required question</div>'); 
     questionElement.hide(); 
    } 

    survey.hideAllQuestions = function() { 
     $('.question:visible').each(function(index, element){ 
      $(element).hide(); 
     }); 
     $('.required-message').each(function(index, element){ 
      $(element).hide(); 
     }); 
    } 

    survey.showNextQuestionSet = function() { 
     this.hideAllQuestions(); 
     this.firstQuestionDisplayed = this.lastQuestionDisplayed+1; 

     do { 
      this.lastQuestionDisplayed++; 
      $('.question-container > div.question:nth-child(' + (this.lastQuestionDisplayed+1) + ')').show(); 
      if (this.questions[this.lastQuestionDisplayed]['break_after'] === true) 
       break; 
     } while (this.lastQuestionDisplayed < this.questions.length-1); 

     this.doButtonStates(); 
    } 

    survey.showPreviousQuestionSet = function() { 
     this.hideAllQuestions(); 
     this.lastQuestionDisplayed = this.firstQuestionDisplayed-1; 

     do { 
      this.firstQuestionDisplayed--; 
      $('.question-container > div.question:nth-child(' + (this.firstQuestionDisplayed+1) + ')').show(); 
      if (this.firstQuestionDisplayed > 0 && this.questions[this.firstQuestionDisplayed-1]['break_after'] === true) 
       break; 
     } while (this.firstQuestionDisplayed > 0); 

     this.doButtonStates(); 
    } 

    survey.doButtonStates = function() { 
     if (this.firstQuestionDisplayed == 0) { 
      $('#backBtn').addClass('invisible'); 
     } 
     else if ($('#backBtn').hasClass('invisible')) { 
      $('#backBtn').removeClass('invisible'); 
     } 

     if (this.lastQuestionDisplayed == this.questions.length-1) { 
      $('#nextBtn').text('Finish'); 
      $('#nextBtn').addClass('blue'); 
     } 
     else if ($('#nextBtn').text() === 'Finish') { 
      $('#nextBtn').text('Continue »'); 
      $('#nextBtn').removeClass('blue'); 
     } 
    } 
})(survey, jQuery); 


$(document).ready(function(){ 
    $.getJSON('questions.json', function(json) { 
     survey.setup_survey(json);   
    }); 
}); 

window.onbeforeunload = function() { 
    return "This will reset all answers that you've already filled in!"; 
} 

Und von hier:

ich analysieren meine JSON Datei:

[ 
    { 
     "text":"Do you know me?", 
     "id":"2", 
     "break_after":true, 
     "required":true, 
     "type":"single-select", 
     "options":[ 
      "YES", 
      "NO" 
     ] 
    }, 
    { 
     "text":"What gets wetter and wetter the more it dries?", 
     "id":"3", 
     "break_after":true, 
     "required":true, 
     "type":"single-select", 
     "options":[ 
      "a car", 
      "a towel", 
      "a plane", 
      "a television" 
     ] 
    }, 
    { 
     "text":"Are you going to?", 
     "id":"4", 
     "type":"text-field-small" 
    }, 
    { 
     "text":"What goes up and down the stairs without moving?", 
     "id":"5", 
     "type":"single-select", 
     "options":[ 
      "a toddler", 
      "an arrow", 
      "towels", 
      "a rug" 
     ] 
    }, 
    { 
     "text":"What can you catch but not throw?", 
     "id":"6", 
     "type":"single-select", 
     "options":[ 
      "a couch", 
      "a cold", 
      "a puppy", 
      "a baseball" 
     ] 
    }, 
    { 
     "text":"I can run but not walk. Wherever I go, thought follows close behind. What am I?", 
     "id":"7", 
     "type":"single-select", 
     "options":[ 
      "a doctor", 
      "a pineapple", 
      "a nose", 
      "pimples" 
     ] 
    }, 
    { 
     "text":"What's black and white and red all over?", 
     "id":"8", 
     "type":"single-select", 
     "options":[ 
      "an embarrased skunk", 
      "a turtle", 
      "a giraffe", 
      "a dog" 
     ] 
    }, 
    { 
     "text":"What goes around the world but stays in a corner?", 
     "id":"9", 
     "type":"single-select", 
     "options":[ 
      "a stamp", 
      "coffee", 
      "a dog", 
      "plants" 
     ] 
    } 
] 

Hier ist was der HTML-Code sieht so aus:

<div class="main"> 

<div><h1 class="title">Test Questionaire</h1><br> 

<div class="question-container"></div> 
<a id="backBtn" href="#" class="button">« Back</a> 
<a id="nextBtn" href="#" class="button">Continue »</a> 
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> 
<script src="survey.js" type="text/javascript"></script> 

</div><div class="completed-message"></div> 
</div></div> 

Irgendeine Idee?

+2

können Sie einfach die URL zu dem Bild hinzufügen? –

+0

ein Daten-URI kann das sein, was Sie brauchen –

+0

Wie kann ich das in meiner JSON-Datei hinzufügen? es ist eine Reihe von Textfragen. –

Antwort

4

Eine Möglichkeit, dies zu erreichen, besteht darin, eine Site wie WebSemantics Image to DataURL converter zu verwenden, um eine Datastringdarstellung des gewünschten Bildes zu erstellen. Da dies ein String kann es in einer JSON-Datei und eingefügt als src Attribut eines HTML-Tag img einmal abgerufen und analysiert, wie so ...

/* JSON example */ 
{ 
    "text": "Some text blah blah...", 
    "img": "data:image/png;base64,iVBORw0KGgoAAA..." 
} 

/* Javascript example */ 
var obj = theParsedJSON; 

var img = '<img src="'+obj.img+'" />'; 
element.innerHTML = img; 

... oder ...

gespeichert werden
var img = new Image(); 

img.addEventListener('load', function() { 
    /* do something with 'this' image: EG */ 
    element.appendChild(this); 
}, false); 

img.src = obj.img; 

Das einzige, was im Auge zu behalten ist, dass Bilddaten URLs ziemlich viel Gewicht auf Ihre JSON-Dateien hinzufügen kann, so dass eine absolute Referenz auf eine Online-Ressource, kann eine bessere Option sein: EG ...

{ 
    "text": "Some text blah blah...", 
    "img": "http://domain.co/path/to/image.jpg" 
} 

Hoffe das hat geholfen. :)

+0

Beachten Sie, dass er, wenn er die Image-Datei in seinem Computer hat, einfach Befehle zum Generieren der base64-Zeichenfolge verwenden könnte, um die Verwendung einer Website eines Drittanbieters zu vermeiden. In MacOS gibt 'base64 ' die base64-Kodierung für den Inhalt von ''. Das gilt auch für die meisten GNU/Linux-Umgebungen. Dann müsste er den String nur als 'data: ; base64, ' formatieren, zum Beispiel: 'data: image/png; base64, .......' –

+0

Ich habe versucht, eine Umfrage hinzuzufügen. doButtonStates = function() aber es hat nicht funktioniert.Ich habe auch folgendes hinzugefügt: { "text": "Was wird feuchter und feuchter, je mehr es trocknet?" "id": "3", "img": "Daten: image/PNG; Base64, asdas" "break_after": true, "erforderlich": true, "type":" Single- wählen Sie“, "Optionen": [ "ein Auto", "ein Handtuch", "eine Ebene", "ein Fernseh" ] }, –

+0

@Gaara: um ein Bild zu einer HTML-Seite Element anhängen dynamisch mit JQuery siehe [diese StackOverflow-Frage] (http://stackoverflow.com/a/14830115/4746328). –

Verwandte Themen