Get value returned in a URL with JS

0

I need to create a very simple script that makes a small calculation.

I have a URL that returns a value in the following format: 10.00, something like this:

link

I need to create a function that takes the value returned from this URL and subtracts that value (-5.00), then prints the result to a <span> that has a specific ID.

<span id="result"></span>

How can I create a function of this type?

    
asked by anonymous 24.08.2018 / 20:40

1 answer

3

To make a request to the API and calculate on the result would look 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 look 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;
}
    
24.08.2018 / 21:04