简体   繁体   中英

How can one write correct HTML to an inline Javascript inside a JSP?

Due to some reasons, I have to load two separate page header HTMLs in my page. One of them is a header for mobile view, and the other is for the desktop view. The rest of my page is responsive. My plan is to load both headers' HTMLs inside a JS that loads on page load and depending on page width populate the correct header's HTML inside my page, and hope the corresponding JS and CSS to load. I am doing this since the JS and CSS of the two header HTMLs are prone to clashing (and I can't tinker with these HTMLs), so I want only of them to load on a page load.

The problem is in writing HTML in JSP inside this inline JS. I repeatedly get errors like "Uncaught SyntaxError: Unexpected token ILLEGAL".

在此处输入图片说明

My code in JSP looks like this:

            <c:when test="${not empty hdrLoggedInHtml and not empty hdrLoggedInHtml_M}">
                <script type="text/javascript">
                    $(document).ready(function(){
                            if($(window).width()>420)
                            {
                                $("#desktopHeader").html('<c:out value="${hdrLoggedInHtml}" escapeXml="false"/>');
                                $("#mobileHeader").html("");                                        
                            }else
                            {
                                $("#mobileHeader").html('<c:out value="${hdrLoggedInHtml_M}" escapeXml="false"/>');
                                $("#desktopHeader").html("");
                            }

                        });
                    });
                </script>

            </c:when>

I tried using fn:escapeXml but that didn't work either. It seems to me that the new line after <html> inside the string is not getting output properly or some invisible character is coming somehow. Please help.

Put hdrLoggedInHtml into a html node which is display:none before it,like:

   <script>
         var global = {} ; global.url = '${url}';global.data = $.parseJSON('${data}');
   </script>

and then,put the script at the bottom of the JSP page ,here is one example:

 <script type="text/javascript">
                $(document).ready(function(){
                        if($(window).width()>420)
                        {
                            $("#desktopHeader").load(global.url,global.data);
                            $("#mobileHeader").html("");                                        
                        }else
                        {
                            $("#mobileHeader").html($('#'));
                            $("#desktopHeader").html("");
                        }

                    });
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM