货币转换器PHP回显弹出窗口

时间:2017-11-09 08:22:00

标签: php html popup

我不知道如何通过API http://api.nbp.pl/的货币换算结果弹出结果。这是我的代码:

<?php

if (isset($_POST['kwota']) && isset($_POST['waluta']) && is_numeric($_POST['kwota']) && is_numeric($_POST['waluta'] )){
switch ($_POST['waluta']) {
case 1:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/usd/'))->rates[0]->mid;
break;
case 2:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/eur/'))->rates[0]->mid;
break;
case 3:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/jpy/'))->rates[0]->mid;
break;
case 4:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/gbp/'))->rates[0]->mid;
break;
case 5:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/aud/'))->rates[0]->mid;
break;
default:
$przelicznik = 1;
}

$wynik = $_POST['kwota']/$przelicznik;
echo $wynik;
}

?>

1 个答案:

答案 0 :(得分:0)

该API是公开的,因此从技术上讲您不需要PHP,您可以获取汇率并直接使用javascript / jQuery显示结果。 这是一个使用jQuery的示例:

<form id="exchange">
    <input type="text" name="price" title="price">
    <select name="currency" title="currency">
        <option value="1">USD</option>
        <option value="2">EUR</option>
        <option value="3">JPY</option>
        <option value="4">GBP</option>
        <option value="5">AUD</option>
    </select>
    <input type="submit" value="calculate">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $('#exchange').on('submit',function(e){
        e.preventDefault();
        var value = $(this).find('[name="price"]').val();
        if(!value) {
            alert("Insert a valid value");
            return false;
        }
        switch ($(this).find('[name="currency"]').val()) {
            case "1":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/usd/';
                break;
            case "2":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/eur/';
                break;
            case "3":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/jpy/';
                break;
            case "4":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/gbp/';
                break;
            case "5":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/aud/';
                break;
            default:
                alert('Error');
                return false;
        }
        console.log($link);
        $.getJSON($link,function(result){
            alert(value/result.rates[0].mid);
        });
    });
</script>