Is it possible to pass GET or POST variable to external javascript

后端 未结 4 1077
广开言路
广开言路 2021-01-26 08:08

I am wondering whether is it possible to pass any variable to external java-script file

For example

I have this

4条回答
  •  抹茶落季
    2021-01-26 08:37

    Using javascript alone, you can do it this way:

    
    

    And then use the javascript function this way:

    // this code would print "hello world" if it was at http://localhost/index.php?var1=hello&var2=world
    var var1 = $_GET('var1');
    var var2 = $_GET('var2');
    document.write(var1 + " " + var2);
    

    To get the parameter needed from the src tag of the javascript you can do something like this:

    // get the src parameter and split it down to the search query string
    var src = document.getElementById('example').src;
    params = src.split('?');
    var var1 = $_GET('var1','?'+params[1]);
    

    Credit to Josh Fraser, from whom I paraphrased this answer. http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/

提交回复
热议问题