1

I am trying to make an Ajax call in my Thymeleaf page. So here is the code

<script>
        function getTodayRequest(){
            console.log("here is today");
            var xhttp=new XMLHttpRequest();
            xhttp.onreadystatechange=function(){
                if(this.readyState==4 && this.status==200){
                document.getElementById("received").innerHTML=
                    this.responseText;
                }
            };
            xhttp.open("GET","URI",true);
        }

</script>

So it complins with the error:

the entity name must immediately follow the '&' in the entity reference. java

and i have changed the & with &amp; and now it looks like:

if(this.readyState==4 &amp;&amp; this.status==200)

but now again it complains with:

Uncaught SyntaxError: Unexpected token ;

In the second &amp;

How can i handle it?

thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
Jeff
  • 7,767
  • 28
  • 85
  • 138
  • I'm no expert but afaik you could wrap the script code in an html comment, i.e. ``. – Thomas Nov 03 '16 at 09:53
  • Unfortunately `&` is not a valid operator in JS. That is an HTML entity. – evolutionxbox Nov 03 '16 at 09:55
  • 3
    Possible duplicate of [The entity name must immediately follow the '&' in the entity reference](http://stackoverflow.com/questions/16303779/the-entity-name-must-immediately-follow-the-in-the-entity-reference) – thatOneGuy Nov 03 '16 at 09:57
  • 1
    What Doctype are you using? Using cdata is necessary in HTML5... http://stackoverflow.com/questions/66837/when-is-a-cdata-section-necessary-within-a-script-tag – evolutionxbox Nov 03 '16 at 10:07

1 Answers1

3

I had a similar issue and I've resolved adding scripting inling from thymelefeaf reference documentation.

So, try to put your javascript code between <script th:inline="javascript"> like next:

<script th:inline="javascript">
/*<![CDATA[*/
     function getTodayRequest(){
            console.log("here is today");
            var xhttp=new XMLHttpRequest();
            xhttp.onreadystatechange=function(){
                if(this.readyState==4 && this.status==200){
                document.getElementById("received").innerHTML=
                    this.responseText;
                }
            };
            xhttp.open("GET","URI",true);
        }
/*]]>*/
</script>
Pau
  • 14,917
  • 14
  • 67
  • 94