0

I see many widgets that allow this :

<script src="http://www.mywebsite.it/widget/widget.js?year=2000" type="text/javascript"></script>

How can I manage that year? I mean, widget.js, on loading, does an ajax call to an aspx page. And I'd like to pass that year to the aspx page.

How can I do it from the .js?

dda
  • 6,030
  • 2
  • 25
  • 34
markzzz
  • 47,390
  • 120
  • 299
  • 507
  • what's the problem here? Why can't you make a simple, plain, vanilla GET request to http://www.mywebsite.it/widget/widget.js?year=2000 ? – Parth Thakkar May 29 '12 at 14:49
  • 2
    Check this other question http://stackoverflow.com/questions/4716612/how-do-i-get-query-string-value-from-script-path – Claudio Redi May 29 '12 at 14:50
  • See: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter – Death May 29 '12 at 14:50
  • year is dinamic! If I call the widget with year=2000 or year=2001 it make different results. So, on widget.js, I must do 2 different ajax call to the aspx. – markzzz May 29 '12 at 14:51
  • Claudio Redi's link is a good one. If you can add an `id` attribute to the tag, you can make things slightly simpler (and more robust, on the chance that not all browsers order scripts the obvious way). – CodeClown42 May 29 '12 at 14:52
  • ok. so? where's the problem? do to ajax requests? Where's the problem? – Parth Thakkar May 29 '12 at 14:52
  • @ParthThakkar: Your suggestion does not exactly deal with the question (read more closely) and assumes that the parameter can be known and hardcoded elsewhere. – CodeClown42 May 29 '12 at 14:55
  • ok wait. either i don't get the question or the question isn't clear. My question: Do you want to make requests to http://www.mywebsite.it/widget/widget.js and pass the parameter `year` to get different variables? – Parth Thakkar May 29 '12 at 14:58
  • @goldilocks : what do you mean as "id attribute to the tag"? Can you give to me an example? – markzzz May 29 '12 at 14:58
  • @markzzz: looks like **dda** beat me to it, see his answer – CodeClown42 May 29 '12 at 15:06
  • Ah! Well, I don't like this approxh with "id". As said by Ashley in the other post, "The punchline is that since scripts in HTML (not XHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it’s triggered". I trust him :) – markzzz May 29 '12 at 15:14

1 Answers1

2

Give your script an id, say "scr1".

<script id="src1" src="http://www.mywebsite.it/widget/widget.js?year=2000" type="text/javascript"></script>

Then you can do:

var myScript = document.getElementById('scr1');
var src=myScript.src;
var p=/[?&]year=(\d+)/
var r=p.exec(src);
// r[1] contains the year

HTH

dda
  • 6,030
  • 2
  • 25
  • 34