1

I would like to pass a list of String from Spring Controller to Javascripts. The Controller :

@PostMapping("/level1")
public String login (Model model){
    List<Question> questions = frageRepository.findAllQuestions();
    List<String> questionText = questions.stream().map(Frage::getText).toList();  
    model.addAttribute("questionText", questionText);
    log.info(spieler.toString());
    return "level1";
}

the body of level1.html

    <body>
       <div class="container mx-auto">
    
        <label class="text-center mt-4" id="thetext">Du liebst Abenteuer und möchte endlich reisen. 
         <br>
            Du hast ein bisschen Geld und das reicht für ein Ticket zur nächsten Insel.<br>
            Unglücklicherweise ist dein Schiff in einem Sturm gesunken. <br>
            Du hat glück, an einen Strand zu landen. <br><br>
            Jetzt musst du die Herausforderungen mit deinen SQL-Kenntnissen meistern.<br>
            Je schneller du die Probleme löst, desto besser ist dein Ranking.<br><br>
            Viel Spaß !!!<br>
        </label>
        <div class="d-flex justify-content-center">
            <input id="startButton" onclick="myFunction()" class="btn-secondary mt-4"
                   type="button" value="next">
        </div>
      </div>
       <script>
          var questionText = [[${questionText}]];
       </script>
       <script th:src="@{/script/questions.js}"></script>
   </body>

the question.js file

var i = 0;

function myFunction() {
    document.getElementById("thetext").innerHTML = questionText[i];
    i++;
}

How can i pass the list questionText to Javascripts code? I want that when the user clicks the next button, the browser will show him the next question in label "thetext" from the list. Or Is there another way to do this? I hope, you can understand me :(

Thank you very much !

6
  • stackoverflow.com/questions/33770839/… Commented Nov 30, 2021 at 16:49
  • What is the problem? What does this output? var listFragenText = [[${questionText}]];? Are you just missing <script th:inline="javascript">? Commented Nov 30, 2021 at 21:03
  • @Metroids yes, i missed th:inline="javascript". it works. Thank you very much Commented Nov 30, 2021 at 22:07
  • @CT11 if you fix it, you can self-answer to share answer :) Commented Dec 5, 2021 at 10:25
  • @Elikill58 i have just inputted th:inline="javascript" in the script tag Commented Dec 6, 2021 at 11:08

1 Answer 1

1

just input th:inline="javascript" in the script tag

<script input th:inline="javascript">
    var questionText = [[${questionText}]];
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.