How to collect variables from a URL, insert them i

2019-07-22 03:37发布

How to collect variables from a URL, insert them into an array and dynamically change a href URLs?

I'm not a developer so please be easy on me here! I am familiar with HTML and not bad at taking snippets of code from various sources and cobbling them together. This is the first time, I've ever decided to reach out for help on a blog like this because I've been looking around and just can't seem to find exactly what I need. Very close and yet so far.. Please help!

What I want to do is:

  1. collect variables from the URL like this (wwww.myurl.com/index.html?var1=1&var2=2&var3=3 etc. etc..)

  2. Take those variables and insert them into an array while stripping out the un-needed parts. I found this code which gets it but prints it on the screen, which I don't need..

    myurl.com/index.html?log=1&pass=2
    

    function addComment()
    {
        var parameters = location.search.substring(1).split("&");
    
        var temp = parameters[0].split("=");
        l = unescape(temp[1]);
    
        temp = parameters[1].split("=");
        c = unescape(temp[1]);
    
        document.getElementById("log").innerHTML = l;
        document.getElementById("pass").innerHTML = c;
    }
    addComment();
    
    
    <p>http://www.myurl.com/</b><span id="log" ></span></p>
    <p>http://www.myurl.com/</b><span id="pass"></span></p>
    
    </script>
    
  3. Dynamically alter a href tags on the fly based on the parameters gathered from the URL.

I found this code which works great to alter the URLs but (a) the variable is gathered from an input form and I need to be able to take them from the URL. (b) I also need several of them (could be like 20) so an array is needed.

<input type="text" id="mySearchBox" />
<a href="http://www.myurl.com/index.html?" onclick="this.href+=+document.getElementById('mySearchBox').value">Enter Parameter</a>

(edited code format)


Regarding the technology... I'm not stuck on any particular language or method but javascript and the jquery seems to be the easiest for me. I haven't done much with PHP and other languages. The easiest method for dummies you can provide the better.

I'm sure this is like elementary school stuff to you out there but I just can't seem to figure it out so your advice is much appreciated!

2条回答
戒情不戒烟
2楼-- · 2019-07-22 04:08

Javascript & jQuery

The first line of the addComment function gets the searchsrtring from the url, wich is everething from (and with) the ? up to (and without) the hash (#) or the end if there is no hash.

After that the first character (?) is removed with substr(1). Finally the string is split at every "&" with .split("&"). All the splited parts are stored in an array. Applying this on an example:

www.myurl.com/index.html?var1=1&var2=2&var3=3

Becomes

["var1=1", "var2=2", "var3=3"]

this array is stored in the variable parameters. Next the first element of the array is splitted at the "=" character. We get

temp = ["var1", "1"]

the second element of temp is unescaped ( to decode special characters from the url like %20 to " " (space) )

To create an object of that, first create an empty object and then fill it like this:

var obj = {};

obj[ temp[0] ] = temp[1];

Doing this on a for loop with all the elements from parameters will get you:

obj = { var1 : 1, var2 : 2, var3 : 3 }

The object that you wanted. This is a very simple parser and may not work properly for more complex values. This is the full code described above:

function getUrlObj() {
  var parameters = location.search.substring(1).split("&");
  var obj = {};
  for( var i = 0; i < parameters.length; ++i) {
    var tmp = parameters[i].split("=");
    obj[ tmp[0] ] = unescape( tmp[1] );
  }
  return obj
}

now to the links:

with your example the onclick event of the link decides which url is loaded. Like this the status bar of the browser will not show the correct destination which is more difficult to debug and less user friendly. A different approach (with jQuery) would be to collect all links from the page and change their href tags according to the url. This can be done after the page (or better the DOM) has been loaded. a jquery example may look like this:

$( function() { //called when dom is ready
  //get url object
  var urlObj = getUrlObj();
  //find all <a> elements on page
  // iterate over elements
  $('a').each(function() {
    // change attribute href
    $(this).attr('href', 'new url goes here');
  });
});

I guess you want to insert some parts of the url object in the new url. what is the initial value of the href attribute? what should it look like in the end?

The initial value may indicate how the url must be changed. The value of an attribute can be accessed with the method .attr('href') in jquery (a second argument would change the value).

a detailed explanation of the .attr() method (and others) can be found in the jquery documentation: http://api.jquery.com/attr/

if you don't want to change all the link elements you may apply a class to the links you want to modify like:

<a class="modify" href...

and then acces those elements with $('.modify') (with dot) instead of $('a').

PHP

If you want to do it with php the code might be a lot simpler because php can handle the url querystring natively. Example:

<a href="<?php echo $_GET["var1"]; ?>.php">link</a>

will result in a link to "1.php" with your example.

UPDATE: (according to the discussion in the comments)

The search query ?iframe1=1&banner1=1&button1=1&button2=2&button3=3 is sent to the server along with the url. PHP can access the values of the search query directly via the magic variable $_GET as pointed out above. $_GET['button1'] will be 1.

To use the variable the file ending has to be .php so the server knows that the contents of the file have to be evaluated. The resulting file will be a normal html file (with php ending).

writing <?php indicates that the following text up to ?> is php code. echo "something"; will print the string something into the resulting html file. A shortcut for printing something to the document is <?="text" ?>. Instead of a string a variable can be printed: <?=$somevar ?>.

Applying this to the example the html file has to updated something like this:

<a target="theiframe" href="www.mysite.com/redirect2external?<?=$_GET['button1'] ?>">a link</a>
<a target="theiframe" href="www.mysite.com/redirect2external?<?=$_GET['button2'] ?>">another link</a>

and so on. Same for the iframe (or the banner):

<iframe name="theiframe" src="www.mysite.com/redirect2external?<?=$_GET['iframe1'] ?>"/>

Another (better) way of combining all the html files into one php file would be to have a number or a string that represents a page. e.g. ?page=somepage (try to avoid special characters and spaces, they might not work properly).

In the php file there will then be a switch for all the pages:

<?php if( $_GET['page'] == "somepage" ) { ?>
  <a target="theiframe" href="www.mysite.com/redirect2external?1">a link</a>
  <a target="theiframe" href="www.mysite.com/redirect2external?2">another link</a>
<?php } elseif( $_GET['page'] == "someotherpage" ) { ?>
  <a target="theiframe" href="www.mysite.com/redirect2external?3">a link</a>
  <a target="theiframe" href="www.mysite.com/redirect2external?4">another link</a>
<?php } //and so on (btw this is a php comment) ?>

The advantages of that approach are:

  1. a shorter url
  2. in the first approach, if a new button is added later you would have to change all the links to that page, adding a buttonx=x in the url. also the additional button would not work if someone uses a bookmark (with the old url) to navigate to that site.
查看更多
Luminary・发光体
3楼-- · 2019-07-22 04:14

Great jQuery plugin for reading and modification of query strings: http://archive.plugins.jquery.com/project/query-object

Just use it to get job done or examine it's source to get answer to your question.

查看更多
登录 后发表回答