To request the API and calculate the result would be something like this:
function makeRequest() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
calcPreco(xmlHttp.responseText);
}
xmlHttp.open("GET", "PONHA_SUA_URL_AQUI", true); // true para asynchronous
xmlHttp.send(null);
}
function calcPreco(preco) {
preco = preco.replace(",", ".");
preco -= 5;
document.getElementById("result").textContent = preco;
}
To recover the price that is in a url parameter would be something like this:
function calcPreco(){
let preco = new URL(location.href).searchParams.get("get");
preco -= 5;
document.getElementById("result").textContent=preco;
}
If you receive a number with ,
in the parameter (something like 10,50
) do:
function calcPreco(){
let preco = new URL(location.href).searchParams.get("get");
preco = preco.replace(",", ".");
preco -= 5;
document.getElementById("result").textContent=preco;
}
Didn’t work here, is it why it returns the value with comma in the URL?
– Wendler
floating numbers in JS are with
.
instead of,
... It would, for example,10.50
instead of10,50
– Lucas Duete
And is there any way to convert this into the function? Because I can’t change it in the API.
– Wendler
yes, just make a value replace... something like
preco.replace(",", ".");
... The response code has been fixed to add this useCase.– Lucas Duete
Weird, it’s not printing the result in span..
– Wendler
A doubt, what would be the searchParams.?
– Wendler
I believe I have misunderstood your problem, this solution takes the value passed by the url... what you really want is to make a request to this url and calculate the price on the right answer?
– Lucas Duete
That, exactly...
– Wendler
checks if the new answer helps you
– Lucas Duete
Do you have a specific way to call this function? I tried it here and I still can’t print the result.
– Wendler
depends on the logic of your code, could be for example:
<body onload="makeRequest()">
– Lucas Duete
Let’s go continue this discussion in chat.
– Wendler