-1

I have some difficulty in understanding how to add an id to an url for sending a request to a server. In fact, my main problem is the position of quotation mark after the equal sign in the third open method. Why it is not used just after Math.random() or just after .asp. Since, if i place the quotation mark just after math.random(), it works but just before math.random() does not. I want to understand what the quotation mark changes here...

xhttp.open(method, url, async);
xhttp.send();

xhttp.open("GET", "demo_get.asp", true);
xhttp.send();

**xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);**
xhttp.send();

For example, I understand what is happening in the following url.

http://localhost/test.php?q=_&p1=_&p2=_

? lets the server know what the ?_GET variables start q, p1, and p2 are parameters and _ is value

mech10
  • 43
  • 7

3 Answers3

0

The Math.random() function returns a float value. You are actually building up a string. So you need to convert it like so:

xhttp.open("GET", "demo_get.asp?t=" + Math.random().toString(), true);
Rolf
  • 78
  • 6
  • ``?t=" + `` why quotation mark is after equal sign. I can not understand this. I got the code from w3schools by the way as below. ``xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true); xhttp.send();`` – mech10 Dec 16 '15 at 16:25
0

The XMLHttpRequest object xhttp sends an asynchronous GET request to the server side script demo_get.asp with a query string t; the value of which is a random number (within the range 0 to 1).

In case of multiple query strings, the query strings are separated using &. For example, the test.php script you mentioned in your question accepts three query strings: q, p1 and p2, values of which are mentioned using = symbol. Most importantly, the query string-value pair are separated using & symbol.

aliasm2k
  • 883
  • 6
  • 12
  • I still did not understand why quotation marks "demo_get.asp?t=" here, not at the end of url(just before the comma). – mech10 Dec 16 '15 at 15:13
0

That is because as it will pass a value like this [ url?t=(a random value) ] as a string value. Here the passing value is "demo_get.asp?t= RANDOM_NUMBER". And now coming to your question--------- if the quotation mark is just before the comma like [ "demo_get.asp?t= Math.random()" ] you can see that Math.random() is no more a function. It will become just a string.

Now you can do like that as new javascript has given a mechanism to do that:

Just type demo_get.asp?t= ${Math.random()} (within back-tick(``) as here back tick is not working in comment) instead of [ "demo_get.asp?t=" + Math.random() ]. I hope this helps :)

luffy
  • 176
  • 1
  • 4