Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript <script> tag error [closed]

Tags:

javascript

I faced a strange issue today at my work place. In a JSP, i had multiple script tags like below, one of which has a empty space in src of the script tag. This JSP is loaded successfully firefox, after i input the values and click submit, the JSP is submitted twice, once with post request and other with get request. The issue is why the form is submitted twice? If anybody had faced this issue. Please respond.

We some how resolved this issue by placing a dummy js file in the script tag, but want to understand the real problem behind it.

<script src="file.js" type="text/javascript"/>
<script src="file1.js" type="text/javascript"/>
<script src="file2.js" type="text/javascript"/>
<script src="file3.js" type="text/javascript"/>
<script src=" " type="text/javascript"/>
<script src="file4.js" type="text/javascript"/>
like image 762
user1748675 Avatar asked Mar 17 '26 01:03

user1748675


2 Answers

In an href or src attribute, an empty string will be treated as a relative URI, and will therefore resolve to the same path as the currently loaded script. So calling the <script> tag with an empty src (assuming the whitespace gets trimmed by JSP), it is like saying:

<script src="thispage.jsp" type="text/javascript"/>

Even though the resource won't be correctly parsed by the browser as JavaScirpt, the server will still send it down to the browser. From the server side, it just looks like a GET request for thispage.jsp and is dutifully responded to, resulting in two requests for thispage.jsp -- the POST you expect and an extraneous GET.

like image 175
Michael Berkowski Avatar answered Mar 18 '26 15:03

Michael Berkowski


Be aware that not all browsers support "self-closing" script tags. It may be that Firefox is misparsing your empty script tag and only including some of your referenced script files.

<script></script>         <!-- this works -->
<script />                <!-- this doesn't -->

Counterintuitive as they are, the reasons are well-explained on this SO answer.

EDIT: I wrote up a demo file, and as of Chrome 22 and IE9, this is the culprit. As long as my server happens to be up, try my demo for yourself.

like image 20
Jeff Bowman Avatar answered Mar 18 '26 15:03

Jeff Bowman