Getting get parameters from url jquery. String parameters (GET) in Javascript


On almost every site you can see links containing parameters after the "?" sign, for example, http://some.site.com/?id=1. Usually a server script handles the processing of such parameters, but sometimes there is a need to find out these parameters inside JavaScript. Today’s story will tell you how to do this.

What are the so-called GET parameters? In fact, this is just an address string, but it is customary that if a “?” character is found in a URL, then all the characters after it are parameters. The interpretation of parameters is standard: first comes the variable name, then the “=" symbol, then the variable value, the variables are separated by the “&” symbol. You can find out the current address in JavaScript by reading the value of window.location. Parse the line after "?" you will have to do it in two passes: first break it into “variable=value” groups, and then break it into its component parts.

Splitting a parameter string is made easier by the fact that JavaScript has a special string function - split(), the result of which will be an array of strings. In order to use it, you first need to create a String object, since this function is a method of this object. This is done simply:

someVar = new String("some text");

Then we divide the string into substrings:

someArray = someVar.split("x");

Where "x" is the symbol for dividing a string into substrings. In order to find a character in a string, you need to use another string function - indexOf():

someVar.indexOf("?");

The introduction to the theory is completed. Let's start practicing. I decided that all GET variables should be stored in two separate global arrays: one stores the names, the other stores the values. Unfortunately JavaScript is not supported associative arrays, so let's use the method I indicated. It is also necessary to save the number of GET variables. Of course, you can always call the function to calculate the size of the array, but stylistically my method is better. And so, global variables and arrays:

var_GET_Keys; // For now an empty array var _GET_Values; var_GET_Count = 0; // no elements yet var _GET_Default = ""

The meaning of the _GET_Default variable will be explained later. Next, I’ll create a get_parseGET() function that will parse URLs and create arrays with variables. At the very beginning, the function creates a String object and checks for the presence of the "?" character in it:

l = get.length; get = get.substr(x+1, l-x);

Now we divide the line into “variable=value” groups, calculate the total number of variables and prepare to create the necessary arrays:

l = get.split("&"); x = 0; _GET_Count = l.length; _GET_Keys = new Array(_GET_Count); _GET_Values ​​= new Array(_GET_Count);

And finally, we divide the resulting groups into two arrays with the names of the variables and their values:

for(i in l) ( get = l[i].split("="); _GET_Keys[x] = get; _GET_Values[x] = get; x++; )

IN in this example the for .. in construction is used, which iterates through all the elements of the array. The syntax of this construction is:

for (key in array) ( // Your actions )

where key is the name of the key that will be selected from array. In the body of the loop, the current element can be accessed by array.

The second function from the library, get_fetchVar(key), allows you to find out the value of a given GET variable. It works by simply iterating over the _GET_Keys array. If the key is not found, it returns the _GET_Default value mentioned above. I would like to note that the _GET_Default value does NOT have to be changed in the library itself - if necessary, this can be done in your HTML code:

_GET_Default="tra la la";

At the very end of the script there is a call to get_parseGET(); and this is where the library ends.

Good bad

    On almost every site you can see links containing parameters after the "?" sign, for example, http://some.site.com/?id=1. Typically, processing such parameters...

    There are several methods to remove an array element in JavaScript. These include the pop and shift methods. The pop method removes the first element from the given array. The shift method removes...

Modern web resources not only provide information to the visitor, but also interact with him. To interact with the user, you need to receive some information from him. There are several methods to retrieve data, very common methods are GET and POST. And accordingly, PHP has support for these data transfer methods GET and POST. Let's see how these methods work.
GET Method Data is transferred using the GET method by appending it to the URL of a script called to process the received information. To explain this method, type in address bar browser URL of the resource and add first a question mark (?) and then the line num=10 . For example

http://domain.ru/script.php?num=10


If you have local server, then usually the domain will be localhost , and then previous entry will look

http://localhost/script.php?num=10


In this case we pass the parameter num equal to 10. To add following parameters The script needs to use the ampersand delimiter (&), for example

http://domain.ru/script.php?num=10&type=new&v=text


IN in this case we passed three parameters to the script: num with the value 10, type with the value "new" and v with the value "text".
To obtain these parameters in the script, you need to use the built-in array $_GET $_GET["num"], $_GET["type"],$_GET["v"] . These array elements will contain the values ​​of the passed parameters. To demonstrate this example, create a script.php file with the following contents



Examination GET method in PHP





And now call this file in the browser

http://path/script.php?num=10&type=new&v=text


and you will see the passed parameters in the browser window. But if you call this file without additional parameters http://path/script.php , you will see the errors that it will give PHP interpreter, that there are no such elements of the $_GET array. More than one article could be devoted to checking the data received from the user, so in this article I will not touch on this point.
As you probably understand, forcing the user to type data in the address bar of the browser is not very good and is completely inconvenient. Therefore, to receive data from the user you need to use html forms. Let's write a simple html form.


Enter the number

Do you have a PC?
Yes
No


Your comment:





Let me comment a little on the created form. Forms are created with the form tag. Form fields are created using the input, select, textarea tags (you can read more). In the form tag action attribute specifies the URL of the script that will receive the form data. In our case, we specified our existing script.php file. The method attribute specifies the method for sending data. We specified the GET method. Now we know which file the form data will be transferred to, and in what way, all that remains is to figure out where to look for it?!
This form data will be passed to the web resource by the browser by appending it to the URL: first there will be a question mark (?), then the parameters will be presented separated by an ampersand (&). The name of the parameter will be taken from the name attribute, which must be specified for any form field. The value of the parameter will depend on the field type. If the field is a text field, the value will be the text entered by the user. If the field is a list, a group of radio buttons or check boxes, then the value of the parameter will be the value of the value attribute of the selected element. Let me explain using our form as an example. If the user enters the number 10 in the input field, then the name of the parameter will be num (the value of the name attribute of the input tag) and the value will be 10 (the number entered by the user). Accordingly, the browser will generate a pair "num=10". If the user selects the "Yes" option from the list, then the name of the parameter will be type (the value of the name attribute of the select tag) and the value will be yes (the value of the value attribute of the option tag). Accordingly, the browser will generate a “type=yes” pair.
Now we will place this form on the forma.php page.



Form for transmitting data using GET and PHP methods



Enter the number

Do you have a PC?
Yes
No


Your comment:







Enter any values ​​in the form fields and click the "Submit" button. After clicking the button, the browser will open another page (script.php) and the data you entered will be displayed in the browser window. I think it’s clear why: the browser will pass the data to the script.php script, and in the script this data will be processed and displayed on the screen.
POST Method Now let's look at how the POST method works.
To send data using the POST method, you need to use HTML forms. As we remember, the method attribute is responsible for the method of sending form data form tag. Therefore, you need to specify the value POST in the method attribute of the form tag. Otherwise, the form can be the same as for the GET method. Let's change our form, which we have already used to transmit data using the GET method, to transmit using the POST method.


Enter the number

Do you have a PC?
Yes
No


Your comment:





As you can see, the form remains the same except for the method and action attributes. The data will now be passed to the script_post.php script. Let's place our form on the forma_post.php page.



Form for transmitting data using POST and PHP methods



Enter the number

Do you have a PC?
Yes
No


Your comment:







Now we need to write a script that will process our form data.
To receive data from the POST method in a script, you need to use the built-in $_POST array. The keys of this array will be the names of the parameters. In our case, we need to use $_POST["num"], $_POST["type"],$_POST["v"] . These array elements will contain the values ​​of the transferred data. As you can see, the difference from using the GET method is expressed only in the use of the $_POST array. Therefore, it will not be difficult for us to write the script_post.php file:



Validating the POST method in PHP





Now open the forma_post.php file in your browser. Enter some data into the form fields and click the "Submit" button. Now, you probably noticed the difference between the POST method and the GET method - the form data did not appear in the address bar of the browser. Data cannot be sent using the POST method through the browser address bar. This is a significant difference to remember.
In PHP, regardless of how the data was sent - the POST method or the GET method - you can get the data using the $_REQUEST array. Comparison of the GET and POST methods When using the GET method, data is transferred by appending to the URL. Thus, they will be visible to the user, which is not always good from a security point of view. Also, the maximum amount of data transferred will depend on the browser - on the maximum permissible number of characters in the browser's address bar.
When using the POST method, the data will not be visible to the user (not displayed in the browser address bar). And therefore they are more secure, and, consequently, the program processing this data is more protected in terms of security. Also, the volume of transmitted data is practically unlimited.
When choosing a data transfer method, you need to take into account the above features and choose the most appropriate method.

Now I will tell you how, using js, we can easily and simply manipulate the URL in the browser without reloading the page. To do this we will use the following function: history.pushState(). It is worth paying attention to the fact that it only works with html5 supported browsers! It has 3 parameters in which we can essentially pass nothing, i.e.:

History.pushState("","","");

In the first of the methods we pass the state of the object. The second is nothing more than the Name (by the way, today it is ignored...). And the third parameter is the URL itself.

In this article we will consider only the third.

In the URL parameter, we simply need to pass a string that will be substituted in the URL from the root of the site.

Let's add a URL

Our URL itself will probably be the simplest: http://localhost/

Var newUrl = "/catalog/?login=myLogin&page=phone"; history.pushState("", "", newUrl);

After executing this script, you will see in the address bar: localhost/catalog/?login=myLogin&page=phone

But be careful. Since our URL has changed. Then when you click refresh the page, the browser will try to go to the new URL. And if your site does not have a /catalog/ section, then you will see a 404 error.

Let's change the existing URL

The second example will go here: localhost/catalog/samsung/?login=myLogin&page=phone

Var arUrl = window.location.pathname.split("/"); var newUrl = "/bazar/"+arUrl+"/"+window.location.search; history.pushState("", "", newUrl);

Line 1: Get the path relative to the host and use split to split it into an array
Line 2: We create a new URL consisting of the word "bazar" + the second key of our array, which contains the word samsung, and at the end we added our get
Line 3: Actually the replacement itself.

After executing this script, you will see in the address bar: localhost/bazar/samsung/?login=myLogin&page=phone

Changing GET parameters

Let's look at the same example.

Var arUrl = window.location.search.split("&"); arUrl = arUrl.slice(1); var arr=; $.each(arUrl,function(i,elem)( arr[i] = elem.split("="); )); var newUrl = arr+"="+arr+"&"+arr+"="+arr; newUrl = window.location.pathname+"?"+newUrl; history.pushState("", "", newUrl);

Of course, this script is a demonstration script and, probably, the simplest one. After its execution, the values ​​of the GET parameters will be swapped in the address bar of the browser. ?login=myLogin&page=phone will change to ?login=phone&page=myLogin. Well, now, in order.

  • line: We get an array of split GET parameters using the & symbol
  • line: Since window.location.searche returns parameters together with the separator - ?, we remove it.
  • line: Create an array
  • line: Let's go through our array
  • line: Divide the value of the keys.
  • line: Collecting new line with parameters.
    Of course, this point could have been done differently, but within the framework of the lesson we will do it in the simplest way.
  • line: Collecting a new URL
  • line replace url
  • After executing the script, our old URL: localhost/catalog/samsung/?login=myLogin&page=phone
    will be replaced with a new one: localhost/catalog/samsung/?login=phone&page=myLogin

    Actually, that's all I wanted to tell you today. Leave your comments and don't forget to share this post on social networks.





    

    2024 gtavrl.ru.